From 3838167dc016aad4e0d14d726e07547074c3b694 Mon Sep 17 00:00:00 2001 From: evazion Date: Sat, 8 Oct 2016 09:07:41 +0000 Subject: [PATCH] Post#unvote!: Return correct score (fixes #2709). vote.destroy sets the score in the database but not on the in-memory post. So just reload the post from the db to get the updated score, don't duplicate the logic of setting it again. --- app/models/post.rb | 6 +----- test/unit/post_test.rb | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/app/models/post.rb b/app/models/post.rb index 26ad1232d..3f7261bc6 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1033,11 +1033,7 @@ class Post < ActiveRecord::Base vote = PostVote.where("post_id = ? and user_id = ?", id, CurrentUser.user.id).first vote.destroy - if vote.score > 0 - self.score -= vote.score - else - self.score += vote.score - end + self.reload end end end diff --git a/test/unit/post_test.rb b/test/unit/post_test.rb index 36aac9934..6173c2179 100644 --- a/test/unit/post_test.rb +++ b/test/unit/post_test.rb @@ -1582,12 +1582,27 @@ class PostTest < ActiveSupport::TestCase should "allow undoing of votes" do user = FactoryGirl.create(:user) post = FactoryGirl.create(:post) + + # We deliberately don't call post.reload until the end to verify that + # post.unvote! returns the correct score even when not forcibly reloaded. CurrentUser.scoped(user, "127.0.0.1") do post.vote!("up") + assert_equal(1, post.score) + post.unvote! - post.reload assert_equal(0, post.score) + assert_nothing_raised {post.vote!("down")} + assert_equal(-1, post.score) + + post.unvote! + assert_equal(0, post.score) + + assert_nothing_raised {post.vote!("up")} + assert_equal(1, post.score) + + post.reload + assert_equal(1, post.score) end end end