A platform for community discussion. Free, open, simple.
FIX: Add DB constraints for post & topic counter cache for `UserStat` (#15626)
Alan Guo Xiang Tan5bd55acf835e
diff --git a/app/models/topic_converter.rb b/app/models/topic_converter.rbindex 925c98c64ba..352258eaece 100644--- a/app/models/topic_converter.rb+++ b/app/models/topic_converter.rb@@ -63,7 +63,7 @@ class TopicConverterprivatedef posters- @posters ||= @topic.posts.distinct.pluck(:user_id).to_a+ @posters ||= @topic.posts.where("post_number > 1").distinct.pluck(:user_id)enddef update_user_statsdiff --git a/app/services/user_stat_count_updater.rb b/app/services/user_stat_count_updater.rbnew file mode 100644index 00000000000..af640417177--- /dev/null+++ b/app/services/user_stat_count_updater.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++class UserStatCountUpdater+ class << self+ def increment!(post, user_stat: nil)+ update!(post, user_stat: user_stat)+ end++ def decrement!(post, user_stat: nil)+ update!(post, user_stat: user_stat, action: :decrement!)+ end++ private++ def update!(post, user_stat: nil, action: :increment!)+ return if !post.topic+ return if post.topic.private_message?+ stat = user_stat || post.user.user_stat++ if post.is_first_post?+ stat.public_send(action, :topic_count)+ elsif post.post_type == Post.types[:regular]+ stat.public_send(action, :post_count)+ end+ end+ end+enddiff --git a/db/migrate/20220118065658_add_constraints_to_user_stat.rb b/db/migrate/20220118065658_add_constraints_to_user_stat.rbnew file mode 100644index 00000000000..a167608cef8--- /dev/null+++ b/db/migrate/20220118065658_add_constraints_to_user_stat.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++class AddConstraintsToUserStat < ActiveRecord::Migration[6.1]+ def up+ execute(<<~SQL)+ UPDATE user_stats+ SET post_count = 0+ WHERE post_count < 0+ SQL++ execute(<<~SQL)+ UPDATE user_stats+ SET topic_count = 0+ WHERE topic_count < 0+ SQL++ execute "ALTER TABLE user_stats ADD CONSTRAINT topic_count_positive CHECK (topic_count >= 0)"+ execute "ALTER TABLE user_stats ADD CONSTRAINT post_count_positive CHECK (post_count >= 0)"+ end++ def down+ execute "ALTER TABLE user_stats DROP CONSTRAINT topic_count_positive"+ execute "ALTER TABLE user_stats DROP CONSTRAINT post_count_positive"+ end+enddiff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rbindex b0d20bd12be..3ac00d847a2 100644--- a/lib/guardian/user_guardian.rb+++ b/lib/guardian/user_guardian.rb@@ -60,6 +60,7 @@ module UserGuardiandef can_delete_user?(user)return false if user.nil? || user.admin?+if is_me?(user)!SiteSetting.enable_discourse_connect &&!user.has_more_posts_than?(SiteSetting.delete_user_self_max_post_count)diff --git a/lib/post_creator.rb b/lib/post_creator.rbindex 3bedd2a1d10..8b7f186e276 100644--- a/lib/post_creator.rb+++ b/lib/post_creator.rb@@ -599,15 +599,10 @@ class PostCreator@user.create_user_stat if @user.user_stat.nil?if @user.user_stat.first_post_created_at.nil?- @user.user_stat.first_post_created_at = @post.created_at+ @user.user_stat.update!(first_post_created_at: @post.created_at)end- unless @post.topic.private_message?- @user.user_stat.post_count += 1 if @post.post_type == Post.types[:regular] && [email protected]_first_post?- @user.user_stat.topic_count += 1 if @post.is_first_post?- end-- @user.user_stat.save!+ UserStatCountUpdater.increment!(@post)if [email protected]_message? && @post.post_type != Post.types[:whisper]@user.update(last_posted_at: @post.created_at)diff --git a/lib/post_destroyer.rb b/lib/post_destroyer.rbindex d9614b45434..8921a715122 100644--- a/lib/post_destroyer.rb+++ b/lib/post_destroyer.rb@@ -155,8 +155,9 @@ class PostDestroyermake_previous_post_the_last_onemark_topic_changedclear_user_posted_flag- Topic.reset_highest(@post.topic_id)end++ Topic.reset_highest(@post.topic_id)trash_public_post_actionstrash_revisionstrash_user_actions@@ -177,7 +178,7 @@ class PostDestroyerendTopicLink.where(link_post_id: @post.id).destroy_allupdate_associated_category_latest_topic- update_user_counts+ update_user_counts if !permanent?TopicUser.update_post_action_cache(post_id: @post.id)DB.after_commit do@@ -387,17 +388,10 @@ class PostDestroyerauthor.create_user_stat if author.user_stat.nil?if @post.created_at == author.user_stat.first_post_created_at- author.user_stat.first_post_created_at = author.posts.order('created_at ASC').first.try(:created_at)- end-- if @post.topic && [email protected]_message?- if @post.post_type == Post.types[:regular] && [email protected]_first_post? && [email protected]?- author.user_stat.post_count -= 1- end- author.user_stat.topic_count -= 1 if @post.is_first_post?+ author.user_stat.update!(first_post_created_at: author.posts.order('created_at ASC').first.try(:created_at))end- author.user_stat.save!+ UserStatCountUpdater.decrement!(@post)if @post.created_at == author.last_posted_atauthor.last_posted_at = author.posts.order('created_at DESC').first.try(:created_at)@@ -407,6 +401,7 @@ class PostDestroyerif @post.is_first_post? && @post.topic && [email protected]_message?# Update stats of all people who repliedcounts = Post.where(post_type: Post.types[:regular], topic_id: @post.topic_id).where('post_number > 1').group(:user_id).count+counts.each do |user_id, count|if user_stat = UserStat.where(user_id: user_id).firstuser_stat.update(post_count: user_stat.post_count - count)diff --git a/lib/post_revisor.rb b/lib/post_revisor.rbindex f3b8aa7333e..8c046392a4e 100644--- a/lib/post_revisor.rb+++ b/lib/post_revisor.rb@@ -437,22 +437,19 @@ class PostRevisorprivate_message = @topic.private_message?prev_owner_user_stat = prev_owner.user_stat+unless private_message- prev_owner_user_stat.post_count -= 1 if @post.post_type == Post.types[:regular]- prev_owner_user_stat.topic_count -= 1 if @post.is_first_post?+ UserStatCountUpdater.decrement!(@post, user_stat: prev_owner_user_stat) if [email protected]?prev_owner_user_stat.likes_received -= likesendif @post.created_at == prev_owner.user_stat.first_post_created_at- prev_owner_user_stat.first_post_created_at = prev_owner.posts.order('created_at ASC').first.try(:created_at)+ prev_owner_user_stat.update!(first_post_created_at: prev_owner.posts.order('created_at ASC').first.try(:created_at))end- prev_owner_user_stat.save!-new_owner_user_stat = new_owner.user_statunless private_message- new_owner_user_stat.post_count += 1 if @post.post_type == Post.types[:regular]- new_owner_user_stat.topic_count += 1 if @post.is_first_post?+ UserStatCountUpdater.increment!(@post, user_stat: new_owner_user_stat) if [email protected]?new_owner_user_stat.likes_received += likesendnew_owner_user_stat.save!diff --git a/spec/components/guardian/user_guardian_spec.rb b/spec/components/guardian/user_guardian_spec.rbindex f07a4062b30..56b532b2984 100644--- a/spec/components/guardian/user_guardian_spec.rb+++ b/spec/components/guardian/user_guardian_spec.rb@@ -243,10 +243,11 @@ describe UserGuardian doendit "isn't allowed when user created too many posts" do- Fabricate(:post, user: user)+ topic = Fabricate(:topic)+ Fabricate(:post, topic: topic, user: user)expect(guardian.can_delete_user?(user)).to eq(true)- Fabricate(:post, user: user)+ Fabricate(:post, topic: topic, user: user)expect(guardian.can_delete_user?(user)).to eq(false)end@@ -319,16 +320,18 @@ describe UserGuardian doendit "correctly respects the delete_user_self_max_post_count setting" do+ topic = Fabricate(:topic)+SiteSetting.delete_user_self_max_post_count = 0expect(guardian.can_delete_user?(user)).to eq(true)- Fabricate(:post, user: user)+ Fabricate(:post, topic: topic, user: user)expect(guardian.can_delete_user?(user)).to eq(false)SiteSetting.delete_user_self_max_post_count = 1expect(guardian.can_delete_user?(user)).to eq(true)- Fabricate(:post, user: user)+ Fabricate(:post, topic: topic, user: user)expect(guardian.can_delete_user?(user)).to eq(false)SiteSetting.delete_user_self_max_post_count = 2diff --git a/spec/components/guardian_spec.rb b/spec/components/guardian_spec.rbindex 4634ff0226c..a16b05b26bc 100644--- a/spec/components/guardian_spec.rb+++ b/spec/components/guardian_spec.rb@@ -1184,6 +1184,8 @@ describe Guardian doenddescribe "can_recover_topic?" do+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:post) { Fabricate(:post, user: user, topic: topic) }it "returns false for a nil user" doexpect(Guardian.new(nil).can_recover_topic?(topic)).to be_falsey@@ -1198,11 +1200,6 @@ describe Guardian doendcontext 'as a moderator' do- before do- topic.save!- post.save!- end-describe 'when post has been deleted' doit "should return the right value" doexpect(Guardian.new(moderator).can_recover_topic?(topic)).to be_falsey@@ -1227,9 +1224,6 @@ describe Guardian dofab!(:group_user) { Fabricate(:group_user) }before do- topic.save!- post.save!-SiteSetting.enable_category_group_moderation = truePostDestroyer.new(moderator, topic.first_post).destroytopic.reload@@ -1262,10 +1256,8 @@ describe Guardian doendcontext 'as a moderator' do- before do- topic.save!- post.save!- end+ fab!(:topic) { Fabricate(:topic, user: user) }+ fab!(:post) { Fabricate(:post, user: user, topic: topic) }describe 'when post has been deleted' doit "should return the right value" dodiff --git a/spec/components/new_post_manager_spec.rb b/spec/components/new_post_manager_spec.rbindex 29ac3ca83b8..ff7085f4d38 100644--- a/spec/components/new_post_manager_spec.rb+++ b/spec/components/new_post_manager_spec.rb@@ -4,12 +4,12 @@ require 'rails_helper'require 'new_post_manager'describe NewPostManager do-+ fab!(:user) { Fabricate(:user) }fab!(:topic) { Fabricate(:topic) }context "default action" doit "creates the post by default" do- manager = NewPostManager.new(topic.user, raw: 'this is a new post', topic_id: topic.id)+ manager = NewPostManager.new(user, raw: 'this is a new post', topic_id: topic.id)result = manager.performexpect(result.action).to eq(:create_post)@@ -25,7 +25,7 @@ describe NewPostManager doit "doesn't enqueue private messages" doSiteSetting.approve_unless_trust_level = 4- manager = NewPostManager.new(topic.user,+ manager = NewPostManager.new(user,raw: 'this is a new post',title: 'this is a new title',archetype: Archetype.private_message,@@ -40,7 +40,7 @@ describe NewPostManager doexpect(result.post).to be_a(Post)# It doesn't enqueue replies to the private message either- manager = NewPostManager.new(topic.user,+ manager = NewPostManager.new(user,raw: 'this is a new reply',topic_id: result.post.topic_id)@@ -56,7 +56,7 @@ describe NewPostManager doendcontext "default handler" do- let(:manager) { NewPostManager.new(topic.user, raw: 'this is new post content', topic_id: topic.id) }+ let(:manager) { NewPostManager.new(user, raw: 'this is new post content', topic_id: topic.id) }context 'with the settings zeroed out' dobefore do@@ -126,8 +126,9 @@ describe NewPostManager docontext 'with a high approval post count, but TL2' dobefore doSiteSetting.approve_post_count = 100- topic.user.trust_level = 2+ user.update!(trust_level: 2)end+it "will return an enqueue result" doresult = NewPostManager.default_handler(manager)expect(result).to be_nil@@ -188,8 +189,9 @@ describe NewPostManager docontext 'with staged moderation setting enabled' dobefore doSiteSetting.approve_unless_staged = true- topic.user.staged = true+ user.update!(staged: true)end+it "will return an enqueue result" doresult = NewPostManager.default_handler(manager)expect(NewPostManager.queue_enabled?).to eq(true)@@ -209,17 +211,17 @@ describe NewPostManager doendcontext 'with a fast typer' do- let(:user) { manager.user }-before douser.update!(trust_level: 0)endit "adds the silence reason in the system locale" domanager = build_manager_with('this is new post content')+I18n.with_locale(:fr) do # Simulate french userresult = NewPostManager.default_handler(manager)end+expect(user.silenced?).to eq(true)expect(user.silence_reason).to eq(I18n.t("user.new_user_typed_too_fast", locale: :en))end@@ -235,12 +237,11 @@ describe NewPostManager doenddef build_manager_with(raw)- NewPostManager.new(topic.user, raw: raw, topic_id: topic.id, first_post_checks: true)+ NewPostManager.new(user, raw: raw, topic_id: topic.id, first_post_checks: true)endendcontext 'with media' do- let(:user) { manager.user }let(:manager_opts) do{raw: 'this is new post content', topic_id: topic.id, first_post_checks: false,@@ -258,7 +259,7 @@ describe NewPostManager doit 'queues the post for review because if it contains embedded media.' doSiteSetting.review_media_unless_trust_level = 1- manager = NewPostManager.new(topic.user, manager_opts)+ manager = NewPostManager.new(user, manager_opts)result = NewPostManager.default_handler(manager)@@ -268,7 +269,7 @@ describe NewPostManager doit 'does not enqueue the post if the poster is a trusted user' doSiteSetting.review_media_unless_trust_level = 0- manager = NewPostManager.new(topic.user, manager_opts)+ manager = NewPostManager.new(user, manager_opts)result = NewPostManager.default_handler(manager)@@ -278,7 +279,7 @@ describe NewPostManager doendcontext "new topic handler" do- let(:manager) { NewPostManager.new(topic.user, raw: 'this is new topic content', title: 'new topic title') }+ let(:manager) { NewPostManager.new(user, raw: 'this is new topic content', title: 'new topic title') }context 'with a high trust level setting for new topics' dobefore doSiteSetting.approve_new_topics_unless_trust_level = 4@@ -351,7 +352,7 @@ describe NewPostManager doendit "calls custom handlers" do- manager = NewPostManager.new(topic.user, raw: 'this post increases counter', topic_id: topic.id)+ manager = NewPostManager.new(user, raw: 'this post increases counter', topic_id: topic.id)result = manager.perform@@ -409,7 +410,7 @@ describe NewPostManager doendit "if nothing returns a result it creates a post" do- manager = NewPostManager.new(topic.user, raw: 'this is a new post', topic_id: topic.id)+ manager = NewPostManager.new(user, raw: 'this is a new post', topic_id: topic.id)result = manager.performdiff --git a/spec/components/post_destroyer_spec.rb b/spec/components/post_destroyer_spec.rbindex 51a2bcc538a..d510e6cc5f5 100644--- a/spec/components/post_destroyer_spec.rb+++ b/spec/components/post_destroyer_spec.rb@@ -995,7 +995,7 @@ describe PostDestroyer doendit 'should destroy internal links when moderator deletes post' do- new_post = Post.create!(user: user, topic: topic, raw: "Link to other topic:\n\n#{url}\n")+ new_post = create_post(user: user, topic: topic, raw: "Link to other topic:\n\n#{url}\n")TopicLink.extract_from(new_post)link_counts = TopicLink.counts_for(guardian, other_topic.reload, [other_post])expect(link_counts.count).to eq(1)diff --git a/spec/fabricators/post_fabricator.rb b/spec/fabricators/post_fabricator.rbindex e7a3e3d19dc..2580bcc836d 100644--- a/spec/fabricators/post_fabricator.rb+++ b/spec/fabricators/post_fabricator.rb@@ -5,6 +5,11 @@ Fabricator(:post) dotopic { |attrs| Fabricate(:topic, user: attrs[:user]) }raw "Hello world"post_type Post.types[:regular]++ # Fabrication bypasses PostCreator, for performance reasons, where the counts are updated so we have to handle this manually here.+ after_save do |post, _transients|+ UserStatCountUpdater.increment!(post)+ endendFabricator(:post_with_long_raw_content, from: :post) dodiff --git a/spec/fabricators/topic_fabricator.rb b/spec/fabricators/topic_fabricator.rbindex b65cd48d7fa..2b7c47605fe 100644--- a/spec/fabricators/topic_fabricator.rb+++ b/spec/fabricators/topic_fabricator.rb@@ -6,6 +6,13 @@ Fabricator(:topic) docategory_id do |attrs|attrs[:category] ? attrs[:category].id : SiteSetting.uncategorized_category_idend++ # Fabrication bypasses PostCreator, for performance reasons, where the counts are updated so we have to handle this manually here.+ after_save do |topic, _transients|+ if !topic.private_message?+ topic.user.user_stat.increment!(:topic_count)+ end+ endendFabricator(:deleted_topic, from: :topic) dodiff --git a/spec/models/topic_converter_spec.rb b/spec/models/topic_converter_spec.rbindex 9c888f8f41d..ed6d050cbde 100644--- a/spec/models/topic_converter_spec.rb+++ b/spec/models/topic_converter_spec.rb@@ -68,7 +68,7 @@ describe TopicConverter doexpect(private_message.user.user_stat.post_count).to eq(0)private_message.convert_to_public_topic(admin)expect(private_message.reload.user.user_stat.topic_count).to eq(1)- expect(private_message.user.user_stat.post_count).to eq(1)+ expect(private_message.user.user_stat.post_count).to eq(0)expect(topic_user.reload.notification_level).to eq(TopicUser.notification_levels[:watching])enddiff --git a/spec/models/topic_link_spec.rb b/spec/models/topic_link_spec.rbindex 2b2ee26f7d8..ef8493f9970 100644--- a/spec/models/topic_link_spec.rb+++ b/spec/models/topic_link_spec.rb@@ -83,15 +83,14 @@ describe TopicLink doit "extracts onebox" doother_topic = Fabricate(:topic, user: user)- other_topic.posts.create(user: user, raw: "some content for the first post")- other_post = other_topic.posts.create(user: user, raw: "some content for the second post")+ Fabricate(:post, topic: other_topic, user: user, raw: "some content for the first post")+ other_post = Fabricate(:post, topic: other_topic, user: user, raw: "some content for the second post")url = "http://#{test_uri.host}/t/#{other_topic.slug}/#{other_topic.id}/#{other_post.post_number}"invalid_url = "http://#{test_uri.host}/t/#{other_topic.slug}/9999999999999999999999999999999"- topic.posts.create(user: user, raw: 'initial post')- post = topic.posts.create(user: user, raw: "Link to another topic:\n\n#{url}\n\n#{invalid_url}")- post.reload+ Fabricate(:post, topic: topic, user: user, raw: 'initial post')+ post = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic:\n\n#{url}\n\n#{invalid_url}")TopicLink.extract_from(post)@@ -110,7 +109,7 @@ describe TopicLink dofab!(:moderator) { Fabricate(:moderator) }let(:post) do- other_topic.posts.create(user: user, raw: "some content")+ Fabricate(:post, topic: other_topic, user: user, raw: "some content")endit 'works' do@@ -120,8 +119,8 @@ describe TopicLink dourl = "http://#{test_uri.host}/t/#{other_topic.slug}/#{other_topic.id}"- topic.posts.create(user: user, raw: 'initial post')- linked_post = topic.posts.create(user: user, raw: "Link to another topic: #{url}")+ Fabricate(:post, topic: topic, user: user, raw: 'initial post')+ linked_post = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic: #{url}")# this is subtle, but we had a bug were second time# TopicLink.extract_from was called a reflection was nuked@@ -169,8 +168,8 @@ describe TopicLink doit 'works without id' doposturl = "http://#{test_uri.host}/t/#{other_topic.slug}"- topic.posts.create(user: user, raw: 'initial post')- linked_post = topic.posts.create(user: user, raw: "Link to another topic: #{url}")+ Fabricate(:post, topic: topic, user: user, raw: 'initial post')+ linked_post = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic: #{url}")TopicLink.extract_from(linked_post)link = topic.topic_links.first@@ -191,8 +190,8 @@ describe TopicLink doposturl = "http://#{test_uri.host}/t/#{other_topic.slug}/#{other_topic.id}"- topic.posts.create(user: user, raw: 'initial post')- linked_post = topic.posts.create(user: user, raw: "Link to another topic: #{url}")+ Fabricate(:post, topic: topic, user: user, raw: 'initial post')+ linked_post = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic: #{url}")TopicLink.extract_from(linked_post)expect(other_topic.reload.topic_links.where(link_post_id: linked_post.id).count).to eq(1)@@ -207,10 +206,11 @@ describe TopicLink dolong_title = "Καλημερα σε ολους και ολες" * 9 # 234 chars, but the encoded slug will be 1224 chars in lengthother_topic = Fabricate(:topic, user: user, title: long_title)expect(other_topic.slug.length).to be > TopicLink.max_url_length- other_topic.posts.create(user: user, raw: 'initial post')++ Fabricate(:post, topic: other_topic, user: user, raw: 'initial post')other_topic_url = "http://#{test_uri.host}/t/#{other_topic.slug}/#{other_topic.id}"- post_with_link = topic.posts.create(user: user, raw: "Link to another topic: #{other_topic_url}")+ post_with_link = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic: #{other_topic_url}")TopicLink.extract_from(post_with_link)topic.reloadlink = topic.topic_links.first@@ -226,10 +226,10 @@ describe TopicLink dotopic_url = "http://#{test_uri.host}/t/#{topic.slug}/#{topic.id}"other_topic = Fabricate(:topic, user: user)- other_topic.posts.create(user: user, raw: 'initial post')+ Fabricate(:post, topic: other_topic, user: user, raw: 'initial post')other_topic_url = "http://#{test_uri.host}/t/#{other_topic.slug}/#{other_topic.id}"- post_with_link = topic.posts.create(user: user, raw: "Link to another topic: #{other_topic_url}")+ post_with_link = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic: #{other_topic_url}")expect { TopicLink.extract_from(post_with_link) }.to_not raise_errorother_topic.reload@@ -240,7 +240,8 @@ describe TopicLink doendcontext "link to a user on discourse" do- let(:post) { topic.posts.create(user: user, raw: "<a href='/u/#{user.username_lower}'>user</a>") }+ let(:post) { Fabricate(:post, topic: topic, user: user, raw: "<a href='/u/#{user.username_lower}'>user</a>") }+before doTopicLink.extract_from(post)end@@ -251,7 +252,7 @@ describe TopicLink doendcontext "link to a discourse resource like a FAQ" do- let(:post) { topic.posts.create(user: user, raw: "<a href='/faq'>faq link here</a>") }+ let(:post) { Fabricate(:post, topic: topic, user: user, raw: "<a href='/faq'>faq link here</a>") }before doTopicLink.extract_from(post)end@@ -262,7 +263,7 @@ describe TopicLink doendcontext "mention links" do- let(:post) { topic.posts.create(user: user, raw: "Hey #{user.username_lower}") }+ let(:post) { Fabricate(:post, topic: topic, user: user, raw: "Hey #{user.username_lower}") }before doTopicLink.extract_from(post)@@ -275,14 +276,14 @@ describe TopicLink docontext "email address" doit "does not extract a link" do- post = topic.posts.create(user: user, raw: "Valid email: [email protected]\n\nInvalid email: rfc822;[email protected]")+ post = Fabricate(:post, topic: topic, user: user, raw: "Valid email: [email protected]\n\nInvalid email: rfc822;[email protected]")TopicLink.extract_from(post)expect(topic.topic_links).to be_blankendendcontext "mail link" do- let(:post) { topic.posts.create(user: user, raw: "[email][email protected][/email]") }+ let(:post) { Fabricate(:post, topic: topic, user: user, raw: "[email][email protected][/email]") }it 'does not extract a link' doTopicLink.extract_from(post)@@ -292,7 +293,7 @@ describe TopicLink docontext "quote links" doit "sets quote correctly" do- linked_post = topic.posts.create(user: user, raw: "my test post")+ linked_post = Fabricate(:post, topic: topic, user: user, raw: "my test post")quoting_post = Fabricate(:post, raw: "[quote=\"#{user.username}, post: #{linked_post.post_number}, topic: #{topic.id}\"]\nquote\n[/quote]")TopicLink.extract_from(quoting_post)@@ -304,7 +305,7 @@ describe TopicLink doendcontext "link to a local attachments" do- let(:post) { topic.posts.create(user: user, raw: '<a class="attachment" href="/uploads/default/208/87bb3d8428eb4783.rb?foo=bar">ruby.rb</a>') }+ let(:post) { Fabricate(:post, topic: topic, user: user, raw: '<a class="attachment" href="/uploads/default/208/87bb3d8428eb4783.rb?foo=bar">ruby.rb</a>') }it "extracts the link" doTopicLink.extract_from(post)@@ -324,7 +325,7 @@ describe TopicLink doendcontext "link to an attachments uploaded on S3" do- let(:post) { topic.posts.create(user: user, raw: '<a class="attachment" href="//s3.amazonaws.com/bucket/2104a0211c9ce41ed67989a1ed62e9a394c1fbd1446.rb">ruby.rb</a>') }+ let(:post) { Fabricate(:post, topic: topic, user: user, raw: '<a class="attachment" href="//s3.amazonaws.com/bucket/2104a0211c9ce41ed67989a1ed62e9a394c1fbd1446.rb">ruby.rb</a>') }it "extracts the link" doTopicLink.extract_from(post)@@ -347,12 +348,12 @@ describe TopicLink dodescribe 'internal link from pm' doit 'works' dopm = Fabricate(:topic, user: user, category_id: nil, archetype: 'private_message')- pm.posts.create(user: user, raw: "some content")+ Fabricate(:post, topic: pm, user: user, raw: "some content")url = "http://#{test_uri.host}/t/topic-slug/#{topic.id}"- pm.posts.create(user: user, raw: 'initial post')- linked_post = pm.posts.create(user: user, raw: "Link to another topic: #{url}")+ Fabricate(:post, topic: pm, user: user, raw: 'initial post')+ linked_post = Fabricate(:post, topic: pm, user: user, raw: "Link to another topic: #{url}")TopicLink.extract_from(linked_post)@@ -367,8 +368,8 @@ describe TopicLink dounlisted_topic = Fabricate(:topic, user: user, visible: false)url = "http://#{test_uri.host}/t/topic-slug/#{topic.id}"- unlisted_topic.posts.create(user: user, raw: 'initial post')- linked_post = unlisted_topic.posts.create(user: user, raw: "Link to another topic: #{url}")+ Fabricate(:post, topic: unlisted_topic, user: user, raw: 'initial post')+ linked_post = Fabricate(:post, topic: unlisted_topic, user: user, raw: "Link to another topic: #{url}")TopicLink.extract_from(linked_post)@@ -384,7 +385,7 @@ describe TopicLink doalternate_uri = URI.parse(Discourse.base_url)url = "http://#{alternate_uri.host}:5678/t/topic-slug/#{other_topic.id}"- post = topic.posts.create(user: user, raw: "Link to another topic: #{url}")+ post = Fabricate(:post, topic: topic, user: user, raw: "Link to another topic: #{url}")TopicLink.extract_from(post)reflection = other_topic.topic_links.firstdiff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rbindex 8c935998238..6a848c009c5 100644--- a/spec/models/topic_spec.rb+++ b/spec/models/topic_spec.rb@@ -2933,12 +2933,12 @@ describe Topic doendit 'returns error message if topic has more posts' do- post_2 = PostCreator.create!(Fabricate(:user), topic_id: topic.id, raw: 'some post content')+ post_2 = create_post(user: user, topic_id: topic.id, raw: 'some post content')PostDestroyer.new(admin, post).destroyexpect(topic.reload.cannot_permanently_delete_reason(Fabricate(:admin))).to eq(I18n.t('post.cannot_permanently_delete.many_posts'))- PostDestroyer.new(admin, post_2).destroy+ PostDestroyer.new(admin, post_2.reload).destroyexpect(topic.reload.cannot_permanently_delete_reason(Fabricate(:admin))).to eq(nil)enddiff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rbindex a664375b119..9b2c2e1f3a5 100644--- a/spec/models/user_spec.rb+++ b/spec/models/user_spec.rb@@ -287,28 +287,31 @@ describe User doenddescribe 'delete posts in batches' do- before_all do- @post1 = Fabricate(:post)- @user = @post1.user- @post2 = Fabricate(:post, topic: @post1.topic, user: @user)- @post3 = Fabricate(:post, user: @user)- @posts = [@post1, @post2, @post3]- @guardian = Guardian.new(Fabricate(:admin))- Fabricate(:reviewable_queued_post, created_by: @user)- end+ fab!(:post1) { Fabricate(:post) }+ fab!(:user) { post1.user }+ fab!(:post2) { Fabricate(:post, topic: post1.topic, user: user) }+ fab!(:post3) { Fabricate(:post, user: user) }+ fab!(:posts) { [post1, post2, post3] }+ fab!(:post_ids) { [post1.id, post2.id, post3.id] }+ fab!(:guardian) { Guardian.new(Fabricate(:admin)) }+ fab!(:reviewable_queued_post) { Fabricate(:reviewable_queued_post, created_by: user) }it 'deletes only one batch of posts' do- deleted_posts = @user.delete_posts_in_batches(@guardian, 1)- expect(Post.where(id: @posts.map(&:id)).count).to eq(2)+ post2+ deleted_posts = user.delete_posts_in_batches(guardian, 1)+ expect(Post.where(id: post_ids).count).to eq(2)expect(deleted_posts.length).to eq(1)- expect(deleted_posts[0]).to eq(@post2)+ expect(deleted_posts[0]).to eq(post2)endit 'correctly deletes posts and topics' do- @user.delete_posts_in_batches(@guardian, 20)- expect(Post.where(id: @posts.map(&:id))).to be_empty- expect(Reviewable.where(created_by: @user).count).to eq(0)- @posts.each do |p|+ posts+ user.delete_posts_in_batches(guardian, 20)++ expect(Post.where(id: post_ids)).to be_empty+ expect(Reviewable.where(created_by: user).count).to eq(0)++ posts.each do |p|if p.is_first_post?expect(Topic.find_by(id: p.topic_id)).to be_nilend@@ -319,10 +322,10 @@ describe User doinvalid_guardian = Guardian.new(Fabricate(:user))expect do- @user.delete_posts_in_batches(invalid_guardian)+ user.delete_posts_in_batches(invalid_guardian)end.to raise_error Discourse::InvalidAccess- @posts.each do |p|+ posts.each do |p|p.reloadexpect(p).to be_presentexpect(p.topic).to be_presentdiff --git a/spec/requests/posts_controller_spec.rb b/spec/requests/posts_controller_spec.rbindex 6c5d1714515..4a751c8e85a 100644--- a/spec/requests/posts_controller_spec.rb+++ b/spec/requests/posts_controller_spec.rb@@ -874,6 +874,8 @@ describe PostsController doenddescribe "when logged in" do+ fab!(:user) { Fabricate(:user) }+before dosign_in(user)end@@ -919,7 +921,7 @@ describe PostsController doendit "doesn't enqueue posts when user first creates a topic" do- user.user_stat.update_column(:topic_count, 1)+ Fabricate(:topic, user: user)Draft.set(user, "should_clear", 0, "{'a' : 'b'}")diff --git a/spec/services/post_owner_changer_spec.rb b/spec/services/post_owner_changer_spec.rbindex 1b34f9b7c3b..5af14753f67 100644--- a/spec/services/post_owner_changer_spec.rb+++ b/spec/services/post_owner_changer_spec.rb@@ -112,7 +112,7 @@ describe PostOwnerChanger dop1user.user_stat.update!(topic_count: 1,- post_count: 1,+ post_count: 0,first_post_created_at: p1.created_at,)@@ -151,7 +151,7 @@ describe PostOwnerChanger doexpect(p2user.topic_count).to eq(0)expect(p2user.post_count).to eq(0)expect(user_a.topic_count).to eq(1)- expect(user_a.post_count).to eq(2)+ expect(user_a.post_count).to eq(1)p1_user_stat = p1user.user_stat