From 1047d7c96b43963783aeb0d0ac5b939a5d003db7 Mon Sep 17 00:00:00 2001 From: evazion Date: Sun, 6 Nov 2016 01:20:10 -0600 Subject: [PATCH] Prevent users from upvoting their own comments. --- app/models/comment_vote.rb | 5 ++++- test/unit/comment_test.rb | 17 +++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/models/comment_vote.rb b/app/models/comment_vote.rb index 28fc3e43c..88ec2d084 100644 --- a/app/models/comment_vote.rb +++ b/app/models/comment_vote.rb @@ -36,7 +36,10 @@ class CommentVote < ActiveRecord::Base end def validate_comment_can_be_down_voted - if is_negative? && comment.creator.is_admin? + if is_positive? && comment.creator == CurrentUser.user + errors.add :base, "You cannot upvote your own comments" + false + elsif is_negative? && comment.creator.is_admin? errors.add :base, "You cannot downvote an admin comment" false else diff --git a/test/unit/comment_test.rb b/test/unit/comment_test.rb index 616462044..abea5c72a 100644 --- a/test/unit/comment_test.rb +++ b/test/unit/comment_test.rb @@ -160,19 +160,28 @@ class CommentTest < ActiveSupport::TestCase user = FactoryGirl.create(:user) post = FactoryGirl.create(:post) c1 = FactoryGirl.create(:comment, :post => post) - comment_vote = c1.vote!("up") + comment_vote = c1.vote!("down") assert_equal([], comment_vote.errors.full_messages) - comment_vote = c1.vote!("up") + comment_vote = c1.vote!("down") assert_equal(["You have already voted for this comment"], comment_vote.errors.full_messages) assert_equal(1, CommentVote.count) - assert_equal(1, CommentVote.last.score) + assert_equal(-1, CommentVote.last.score) c2 = FactoryGirl.create(:comment, :post => post) - comment_vote = c2.vote!("up") + comment_vote = c2.vote!("down") assert_equal([], comment_vote.errors.full_messages) assert_equal(2, CommentVote.count) end + should "not allow upvotes by the creator" do + user = FactoryGirl.create(:user) + post = FactoryGirl.create(:post) + c1 = FactoryGirl.create(:comment, :post => post) + comment_vote = c1.vote!("up") + + assert_equal(["You cannot upvote your own comments"], comment_vote.errors.full_messages) + end + should "allow undoing of votes" do user = FactoryGirl.create(:user) post = FactoryGirl.create(:post)