Refactoring: Move 'vote' action to Comments::VotesControllers

As far as possible I think the code is clearer if we use CRUD actions
rather than custom actions. This will make it easier to add the action
to remove votes in the next commit.

Note that we are adding this line as we need to validate it that a vote
can be created on a comment by the current user:

```authorize! :create, Vote.new(voter: current_user, votable: @comment)```

We have done it this way and not with the following code as you might
expect, as this way two votes are created instead of one.

```load_and_authorize_resource through: :comment, through_association: :votes_for```

This line tries to load the resource @comment and through the association
"votes_for" it tries to create a new vote associated to that debate.
Therefore a vote is created when trying to authorise the resource and
then another one in the create action, when calling @comment.vote.
This commit is contained in:
taitus
2023-09-20 16:08:44 +02:00
parent b39b64a674
commit f87a332c3e
10 changed files with 58 additions and 15 deletions

View File

@@ -0,0 +1,15 @@
require "rails_helper"
describe Comments::VotesController do
let(:comment) { create(:comment) }
describe "POST create" do
it "allows voting" do
sign_in create(:user)
expect do
post :create, xhr: true, params: { comment_id: comment.id, value: "yes" }
end.to change { comment.reload.votes_for.size }.by(1)
end
end
end