Browse Source

Adds def update to activity controller, and unit tests

Lou 3 years ago
parent
commit
26ee834214

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

@@ -1,6 +1,7 @@
1 1
 class Api::V1::ActivitiesController < ApplicationController
2 2
   before_action :set_activity, only: %i[show update destroy]
3 3
   before_action :check_login
4
+  before_action :check_owner, only: %i[update]
4 5
 
5 6
   def index
6 7
     render json: Activity.all
@@ -19,6 +20,14 @@ class Api::V1::ActivitiesController < ApplicationController
19 20
     end
20 21
   end
21 22
 
23
+  def update
24
+    if @activity.update(activity_params)
25
+      render json: @product
26
+    else
27
+      render json: @product.erros, status: :unprocessable_entity
28
+    end
29
+  end
30
+
22 31
   private
23 32
 
24 33
   # Only allow a trusted parameter "white list" through.
@@ -29,4 +38,8 @@ class Api::V1::ActivitiesController < ApplicationController
29 38
   def set_activity
30 39
     @activity = Activity.find(params[:id])
31 40
   end
41
+
42
+  def check_owner
43
+    head :forbidden unless @activity.author_id == current_user&.id
44
+  end
32 45
 end

+ 25
- 1
test/controllers/api/v1/activities_controller_test.rb View File

@@ -52,4 +52,28 @@ class Api::V1::ActivitiesControllerTest < ActionDispatch::IntegrationTest
52 52
     end
53 53
     assert_response :forbidden
54 54
   end
55
-end
55
+
56
+  #UPDATE
57
+  test "should update activity" do
58
+    patch api_v1_activity_url(@activity),
59
+    params: { activity: { name: "Updated name" } },
60
+    headers: { Authorization: JsonWebToken.encode(user_id: @activity.author_id) },
61
+    as: :json
62
+    assert_response :success
63
+  end
64
+
65
+  test "should forbid update activity - not connected" do
66
+    patch api_v1_activity_url(@activity),
67
+    params: { activity: { name: "Updated name" } },
68
+    as: :json
69
+    assert_response :forbidden
70
+  end
71
+
72
+  test "should forbid update activity - not owner" do
73
+    patch api_v1_activity_url(@activity),
74
+    params: { activity: { name: "Updated name" } },
75
+    headers: { Authorization: JsonWebToken.encode(user_id: users(:two).id) },
76
+    as: :json
77
+    assert_response :forbidden
78
+  end
79
+end

+ 5
- 0
test/fixtures/users.yml View File

@@ -3,4 +3,9 @@
3 3
 one:
4 4
   email: one@one.com
5 5
   username: OneUsername
6
+  password_digest: <%= BCrypt::Password.create('g00d_pa$$') %>
7
+
8
+two:
9
+  email: two@two.com
10
+  username: TwoUsername
6 11
   password_digest: <%= BCrypt::Password.create('g00d_pa$$') %>

Loading…
Cancel
Save