Browse Source

Adds def create to activities controllers, and unit test

Lou 3 years ago
parent
commit
7249e53c27

+ 11
- 2
app/controllers/api/v1/activities_controller.rb View File

@@ -1,7 +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
-  
4
+
5 5
   def index
6 6
     render json: Activity.all
7 7
   end
@@ -10,11 +10,20 @@ class Api::V1::ActivitiesController < ApplicationController
10 10
     render json: Activity.find(params[:id])
11 11
   end
12 12
 
13
+  def create
14
+    activity = current_user.created_activities.build(activity_params)
15
+    if activity.save
16
+      render json: activity, status: :created
17
+    else
18
+      render json: { errors: activity.errors }, status: :unprocessable_entity
19
+    end
20
+  end
21
+
13 22
   private
14 23
 
15 24
   # Only allow a trusted parameter "white list" through.
16 25
   def activity_params
17
-    params.require(:user).permit(:name, :author_id, :description, :client)
26
+    params.require(:activity).permit(:name, :author_id, :description, :client)
18 27
   end
19 28
 
20 29
   def set_activity

+ 21
- 0
test/controllers/api/v1/activities_controller_test.rb View File

@@ -3,6 +3,7 @@ require "test_helper"
3 3
 class Api::V1::ActivitiesControllerTest < ActionDispatch::IntegrationTest
4 4
   setup do
5 5
     @activity = activities(:one)
6
+    @user = users(:one)
6 7
   end
7 8
   
8 9
   #INDEX
@@ -31,4 +32,24 @@ class Api::V1::ActivitiesControllerTest < ActionDispatch::IntegrationTest
31 32
     as: :json
32 33
     assert_response :forbidden
33 34
   end
35
+
36
+  #CREATE
37
+  test "should create activity" do
38
+    assert_difference("Activity.count") do
39
+      post api_v1_activities_url,
40
+      params: { activity: { name: @activity.name, client: @activity.client, description: @activity.description, author_id: @user }},
41
+      headers: { Authorization: JsonWebToken.encode(user_id: @activity.author_id) },
42
+      as: :json
43
+    end
44
+    assert_response :created
45
+  end
46
+
47
+  test "should forbid create activity" do
48
+    assert_no_difference "Activity.count" do
49
+      post api_v1_activities_url,
50
+      params: { activity: { name: @activity.name, client: @activity.client, description: @activity.description, author_id: @user } },
51
+      as: :json
52
+    end
53
+    assert_response :forbidden
54
+  end
34 55
 end

+ 0
- 6
test/models/user_test.rb View File

@@ -22,10 +22,4 @@ class UserTest < ActiveSupport::TestCase
22 22
   user = User.new(email: other_user.email, username: "UserTest", password_digest: "test_password")
23 23
   assert_not user.valid?
24 24
   end
25
-
26
-  test 'destroy user should destroy linked activity' do
27
-    assert_difference('Activity.count', -1) do
28
-      users(:one).destroy
29
-    end
30
-  end
31 25
 end

Loading…
Cancel
Save