Browse Source

Add update and destroy defs to user controller, and test units

Lou 3 years ago
parent
commit
f8aae15cdc

+ 13
- 0
app/controllers/api/v1/users_controller.rb View File

@@ -19,6 +19,19 @@ class Api::V1::UsersController < ApplicationController
19 19
     end
20 20
   end
21 21
 
22
+  def update
23
+    if @user.update(user_params)
24
+      render json: @user, status: :ok
25
+    else
26
+      render json: @user.errors, status: :unprocessable_entity
27
+    end
28
+  end
29
+
30
+  def destroy
31
+    @user.destroy
32
+    head 204
33
+  end
34
+
22 35
   private
23 36
 
24 37
   # Only allow a trusted parameter "white list" through.

+ 18
- 0
app/controllers/concerns/authenticable.rb View File

@@ -0,0 +1,18 @@
1
+module Authenticable
2
+  def current_user
3
+    return @current_user if @current_user
4
+
5
+    header = request.headers['Authorization']
6
+    return nil if header.nil?
7
+
8
+    decoded = JsonWebToken.decode(header)
9
+
10
+    @current_user = User.find(decoded[:user_id]) rescue ActiveRecord::RecordNotFound
11
+  end
12
+
13
+  protected
14
+
15
+  def check_login
16
+    head :forbidden unless self.current_user
17
+  end
18
+end

+ 27
- 1
test/controllers/api/v1/users_controller_test.rb View File

@@ -34,5 +34,31 @@ class Api::V1::UsersControllerTest < ActionDispatch::IntegrationTest
34 34
       post api_v1_users_url, params: { user: { email: "test@email.com", username: @user.username, password: '123456' } }, as: :json
35 35
     end
36 36
     assert_response :unprocessable_entity
37
-  end 
37
+  end
38
+
39
+  #UPDATE
40
+  test "should update user" do
41
+    patch api_v1_user_url(@user), params: { user: { email: @user.email, username: @user.username, password: '123456' } }, as: :json
42
+    assert_response :success
43
+  end
44
+
45
+  # test "should not update user when invalid params are sent" do
46
+  #   patch api_v1_user_url(@user), params: { user: { email: 'bad_email', username: @user.username, password: '123456' } }, as: :json
47
+  #   assert_response :unprocessable_entity
48
+  # end
49
+
50
+  #DESTROY 
51
+  test "should destroy user" do
52
+    assert_difference('User.count', -1) do
53
+      delete api_v1_user_url(@user), as: :json
54
+    end
55
+    assert_response :no_content
56
+  end
57
+
58
+  # test "should forbid destroy user" do
59
+  #   assert_no_difference('User.count') do
60
+  #     delete api_v1_user_url(@user), as: :json
61
+  #   end
62
+  #   assert_response :forbidden
63
+  # end
38 64
 end

Loading…
Cancel
Save