diff --git a/app/models/topic.rb b/app/models/topic.rb index 0787d52734c..38c489dbf2b 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -546,10 +546,9 @@ class Topic < ActiveRecord::Base topic_id: self.id, skip_validations: true, custom_fields: opts[:custom_fields]) - new_post = creator.create - increment!(:moderator_posts_count) if new_post.persisted? - if new_post.present? + if (new_post = creator.create) && new_post.present? + increment!(:moderator_posts_count) if new_post.persisted? # If we are moving posts, we want to insert the moderator post where the previous posts were # in the stream, not at the end. new_post.update_attributes!(post_number: opts[:post_number], sort_order: opts[:post_number]) if opts[:post_number].present? diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb index e1f48980ffd..447bf81cfb2 100644 --- a/spec/models/topic_spec.rb +++ b/spec/models/topic_spec.rb @@ -6,6 +6,7 @@ require_dependency 'post_destroyer' describe Topic do let(:now) { Time.zone.local(2013,11,20,8,0) } + let(:user) { Fabricate(:user) } it { is_expected.to validate_presence_of :title } @@ -312,8 +313,6 @@ describe Topic do end context "secure categories" do - - let(:user) { Fabricate(:user) } let(:category) { Fabricate(:category, read_restricted: true) } before do @@ -499,20 +498,36 @@ describe Topic do end context 'moderator posts' do - before do - @moderator = Fabricate(:moderator) - @topic = Fabricate(:topic) - @mod_post = @topic.add_moderator_post(@moderator, "Moderator did something. http://discourse.org", post_number: 999) - end + let(:moderator) { Fabricate(:moderator) } + let(:topic) { Fabricate(:topic) } it 'creates a moderator post' do - expect(@mod_post).to be_present - expect(@mod_post.post_type).to eq(Post.types[:moderator_action]) - expect(@mod_post.post_number).to eq(999) - expect(@mod_post.sort_order).to eq(999) - expect(@topic.topic_links.count).to eq(1) - @topic.reload - expect(@topic.moderator_posts_count).to eq(1) + mod_post = topic.add_moderator_post( + moderator, + "Moderator did something. http://discourse.org", + post_number: 999 + ) + + expect(mod_post).to be_present + expect(mod_post.post_type).to eq(Post.types[:moderator_action]) + expect(mod_post.post_number).to eq(999) + expect(mod_post.sort_order).to eq(999) + expect(topic.topic_links.count).to eq(1) + expect(topic.reload.moderator_posts_count).to eq(1) + end + + context "when moderator post fails to be created" do + before do + user.toggle!(:blocked) + end + + it "should not increment moderator_posts_count" do + expect(topic.moderator_posts_count).to eq(0) + + topic.add_moderator_post(user, "winter is never coming") + + expect(topic.moderator_posts_count).to eq(0) + end end end