Преглед на файлове

Add def index/show/create to users controller, and test units

Lou преди 3 години
родител
ревизия
d28c6612d0
променени са 2 файла, в които са добавени 70 реда и са изтрити 0 реда
  1. 32
    0
      app/controllers/api/v1/users_controller.rb
  2. 38
    0
      test/controllers/api/v1/users_controller_test.rb

+ 32
- 0
app/controllers/api/v1/users_controller.rb Целия файл

@@ -0,0 +1,32 @@
1
+class Api::V1::UsersController < ApplicationController
2
+  before_action :set_user, only: %i[show update destroy]
3
+
4
+  def index
5
+    render json: User.all
6
+  end
7
+
8
+  def show
9
+    render json: User.find(params[:id])
10
+  end
11
+
12
+  def create
13
+    @user = User.new(user_params)
14
+
15
+    if @user.save
16
+      render json: @user, status: :created
17
+    else
18
+      render json: @user.errors, status: :unprocessable_entity
19
+    end
20
+  end
21
+
22
+  private
23
+
24
+  # Only allow a trusted parameter "white list" through.
25
+  def user_params
26
+    params.require(:user).permit(:email, :username, :password)
27
+  end
28
+
29
+  def set_user
30
+    @user = User.find(params[:id])
31
+  end
32
+end

+ 38
- 0
test/controllers/api/v1/users_controller_test.rb Целия файл

@@ -0,0 +1,38 @@
1
+require "test_helper"
2
+
3
+class Api::V1::UsersControllerTest < ActionDispatch::IntegrationTest
4
+  setup do
5
+    @user = users(:one)
6
+  end
7
+
8
+  #SHOW 
9
+  test "should show user" do
10
+    get api_v1_user_url(@user), as: :json
11
+    assert_response :success
12
+    # Test to ensure response contains the correct email
13
+    json_response = JSON.parse(self.response.body)
14
+    assert_equal @user.email, json_response['email']
15
+  end
16
+
17
+  #CREATE
18
+  test "should create user" do
19
+    assert_difference('User.count') do
20
+      post api_v1_users_url, params: { user: { email: 'test@test.org', username: 'new_user_name', password: '123456' } }, as: :json
21
+    end
22
+    assert_response :created
23
+  end
24
+
25
+  test "should not create user with taken email" do
26
+    assert_no_difference('User.count') do
27
+      post api_v1_users_url, params: { user: { email: @user.email, username: 'username_test', password: '123456' } }, as: :json
28
+    end
29
+    assert_response :unprocessable_entity
30
+  end
31
+
32
+  test "should not create user with taken username" do
33
+    assert_no_difference('User.count') do
34
+      post api_v1_users_url, params: { user: { email: "test@email.com", username: @user.username, password: '123456' } }, as: :json
35
+    end
36
+    assert_response :unprocessable_entity
37
+  end 
38
+end

Loading…
Отказ
Запис