A platform for community discussion. Free, open, simple.
DEV: Update the rubocop-discourse gem
Loïc Guitaut0f4beab0fbbd
diff --git a/Gemfile.lock b/Gemfile.lockindex 958bfb6056d..ed44c90dd22 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -191,6 +191,7 @@ GEMsimpleidn (~> 0.2)jwt (2.7.1)kgio (2.11.4)+ language_server-protocol (3.17.0.3)libv8-node (18.16.0.0)libv8-node (18.16.0.0-aarch64-linux)libv8-node (18.16.0.0-arm64-darwin)@@ -409,8 +410,9 @@ GEMrspec-core (>= 2.14)rtlcss (0.2.1)mini_racer (>= 0.6.3)- rubocop (1.52.1)+ rubocop (1.53.0)json (~> 2.3)+ language_server-protocol (>= 3.17.0)parallel (~> 1.10)parser (>= 3.2.2.3)rainbow (>= 2.2.2, < 4.0)@@ -423,7 +425,7 @@ GEMparser (>= 3.2.1.0)rubocop-capybara (2.18.0)rubocop (~> 1.41)- rubocop-discourse (3.2.0)+ rubocop-discourse (3.3.0)rubocop (>= 1.1.0)rubocop-rspec (>= 2.0.0)rubocop-factory_bot (2.23.1)diff --git a/plugins/chat/spec/jobs/regular/chat/auto_join_channel_batch_spec.rb b/plugins/chat/spec/jobs/regular/chat/auto_join_channel_batch_spec.rbindex 9ccb28332c8..b1ed2bdea9f 100644--- a/plugins/chat/spec/jobs/regular/chat/auto_join_channel_batch_spec.rb+++ b/plugins/chat/spec/jobs/regular/chat/auto_join_channel_batch_spec.rb@@ -3,13 +3,15 @@require "rails_helper"describe Jobs::Chat::AutoJoinChannelBatch do+ subject(:job) { described_class.new }+describe "#execute" dofab!(:category) { Fabricate(:category) }let!(:user) { Fabricate(:user, last_seen_at: 15.minutes.ago) }let(:channel) { Fabricate(:chat_channel, auto_join_users: true, chatable: category) }it "joins all valid users in the batch" do- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_users_follows_channel(channel, [user])end@@ -17,7 +19,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "doesn't join users outside the batch" doanother_user = Fabricate(:user, last_seen_at: 15.minutes.ago)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_users_follows_channel(channel, [user])assert_user_skipped(channel, another_user)@@ -26,7 +28,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "doesn't join suspended users" douser.update!(suspended_till: 1.year.from_now)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_user_skipped(channel, user)end@@ -34,7 +36,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "doesn't join users last_seen more than 3 months ago" douser.update!(last_seen_at: 4.months.ago)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_user_skipped(channel, user)end@@ -42,13 +44,13 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "joins users with last_seen set to null" douser.update!(last_seen_at: nil)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_users_follows_channel(channel, [user])endit "does nothing if the channel is invalid" do- subject.execute(chat_channel_id: -1, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: -1, starts_at: user.id, ends_at: user.id)assert_user_skipped(channel, user)end@@ -57,13 +59,13 @@ describe Jobs::Chat::AutoJoinChannelBatch dodirect_message = Fabricate(:direct_message)channel.update!(chatable: direct_message)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_user_skipped(channel, user)endit "enqueues the user count update job and marks the channel user count as stale" do- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)expect_job_enqueued(job: Jobs::Chat::UpdateChannelUserCount,args: {@@ -81,7 +83,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doargs: {chat_channel_id: channel.id,},- ) { subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id) }+ ) { job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id) }expect(channel.reload.user_count_stale).to eq(false)end@@ -89,13 +91,13 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "ignores users without chat_enabled" douser.user_option.update!(chat_enabled: false)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_user_skipped(channel, user)endit "sets the join reason to automatic" do- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)new_membership = Chat::UserChatChannelMembership.find_by(user: user, chat_channel: channel)expect(new_membership.automatic?).to eq(true)@@ -104,7 +106,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "skips anonymous users" douser_2 = Fabricate(:anonymous)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)assert_users_follows_channel(channel, [user])assert_user_skipped(channel, user_2)@@ -113,7 +115,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "skips non-active users" douser_2 = Fabricate(:user, active: false, last_seen_at: 15.minutes.ago)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)assert_users_follows_channel(channel, [user])assert_user_skipped(channel, user_2)@@ -122,7 +124,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "skips staged users" douser_2 = Fabricate(:user, staged: true, last_seen_at: 15.minutes.ago)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)assert_users_follows_channel(channel, [user])assert_user_skipped(channel, user_2)@@ -131,7 +133,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "adds every user in the batch" douser_2 = Fabricate(:user, last_seen_at: 15.minutes.ago)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user_2.id)assert_users_follows_channel(channel, [user, user_2])end@@ -139,7 +141,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "publishes a message only to joined users" domessages =MessageBus.track_publish("/chat/new-channel") do- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)endexpect(messages.size).to eq(1)@@ -156,7 +158,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doit "only joins group members with access to the category" doanother_user = Fabricate(:user, last_seen_at: 15.minutes.ago)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: another_user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: another_user.id)assert_users_follows_channel(channel, [user])assert_user_skipped(channel, another_user)@@ -167,7 +169,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doFabricate(:category_group, category: category, group: second_chatters_group)second_chatters_group.add(user)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: user.id)assert_users_follows_channel(channel, [user])end@@ -176,7 +178,7 @@ describe Jobs::Chat::AutoJoinChannelBatch doanother_user = Fabricate(:user, last_seen_at: 15.minutes.ago)chatters_group.add(another_user)- subject.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: another_user.id)+ job.execute(chat_channel_id: channel.id, starts_at: user.id, ends_at: another_user.id)assert_users_follows_channel(channel, [user, another_user])end@@ -195,7 +197,7 @@ describe Jobs::Chat::AutoJoinChannelBatch do)non_chatters_group.add(another_user)- subject.execute(+ job.execute(chat_channel_id: readonly_channel.id,starts_at: another_user.id,ends_at: another_user.id,@@ -227,7 +229,7 @@ describe Jobs::Chat::AutoJoinChannelBatch do)other_group.add(another_user)- subject.execute(+ job.execute(chat_channel_id: private_channel.id,starts_at: another_user.id,ends_at: another_user.id,diff --git a/plugins/chat/spec/jobs/regular/chat/delete_user_messages_spec.rb b/plugins/chat/spec/jobs/regular/chat/delete_user_messages_spec.rbindex 224d382a3c5..1cb3f1c8da3 100644--- a/plugins/chat/spec/jobs/regular/chat/delete_user_messages_spec.rb+++ b/plugins/chat/spec/jobs/regular/chat/delete_user_messages_spec.rb@@ -2,12 +2,14 @@RSpec.describe Jobs::Chat::DeleteUserMessages dodescribe "#execute" do+ subject(:execute) { described_class.new.execute(user_id: user_1) }+fab!(:user_1) { Fabricate(:user) }fab!(:channel) { Fabricate(:chat_channel) }fab!(:chat_message) { Fabricate(:chat_message, chat_channel: channel, user: user_1) }it "deletes messages from the user" do- subject.execute(user_id: user_1)+ executeexpect { chat_message.reload }.to raise_error(ActiveRecord::RecordNotFound)end@@ -16,7 +18,7 @@ RSpec.describe Jobs::Chat::DeleteUserMessages douser_2 = Fabricate(:user)user_2_message = Fabricate(:chat_message, chat_channel: channel, user: user_2)- subject.execute(user_id: user_1)+ executeexpect(user_2_message.reload).to be_presentend@@ -24,7 +26,7 @@ RSpec.describe Jobs::Chat::DeleteUserMessages doit "deletes trashed messages" dochat_message.trash!- subject.execute(user_id: user_1)+ executeexpect(Chat::Message.with_deleted.where(id: chat_message.id)).to be_emptyenddiff --git a/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb b/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rbindex 7ac9d674613..db432fbdcda 100644--- a/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb+++ b/plugins/chat/spec/jobs/regular/chat/notify_mentioned_spec.rb@@ -3,6 +3,8 @@require "rails_helper"describe Jobs::Chat::NotifyMentioned do+ subject(:job) { described_class.new }+fab!(:user_1) { Fabricate(:user) }fab!(:user_2) { Fabricate(:user) }fab!(:public_channel) { Fabricate(:category_channel) }@@ -47,7 +49,7 @@ describe Jobs::Chat::NotifyMentioned do)MessageBus.track_publish("/chat/notification-alert/#{user.id}") do- subject.execute(+ job.execute(chat_message_id: message.id,timestamp: message.created_at,to_notify_ids_map: to_notify_ids_map,@@ -58,7 +60,7 @@ describe Jobs::Chat::NotifyMentioned doenddef track_core_notification(user: user_2, message:, to_notify_ids_map:)- subject.execute(+ job.execute(chat_message_id: message.id,timestamp: message.created_at,to_notify_ids_map: to_notify_ids_map,@@ -175,7 +177,7 @@ describe Jobs::Chat::NotifyMentioned doPostAlerter.expects(:push_notification).never- subject.execute(+ job.execute(chat_message_id: message.id,timestamp: message.created_at,to_notify_ids_map: to_notify_ids_map,@@ -204,7 +206,7 @@ describe Jobs::Chat::NotifyMentioned doPostAlerter.expects(:push_notification).never- subject.execute(+ job.execute(chat_message_id: message.id,timestamp: message.created_at,to_notify_ids_map: to_notify_ids_map,@@ -248,7 +250,7 @@ describe Jobs::Chat::NotifyMentioned do},)- subject.execute(+ job.execute(chat_message_id: message.id,timestamp: message.created_at,to_notify_ids_map: to_notify_ids_map,diff --git a/plugins/chat/spec/jobs/regular/chat/send_message_notifications_spec.rb b/plugins/chat/spec/jobs/regular/chat/send_message_notifications_spec.rbindex 2739339fc35..93d395da9ac 100644--- a/plugins/chat/spec/jobs/regular/chat/send_message_notifications_spec.rb+++ b/plugins/chat/spec/jobs/regular/chat/send_message_notifications_spec.rb@@ -1,13 +1,15 @@# frozen_string_literal: trueRSpec.describe Jobs::Chat::SendMessageNotifications do+ subject(:job) { described_class.new }+describe "#execute" docontext "when the message doesn't exist" doit "does nothing" doChat::Notifier.any_instance.expects(:notify_new).neverChat::Notifier.any_instance.expects(:notify_edit).never- subject.execute(eason: "new", timestamp: 1.minute.ago)+ job.execute(reason: "new", timestamp: 1.minute.ago)endend@@ -18,32 +20,28 @@ RSpec.describe Jobs::Chat::SendMessageNotifications doChat::Notifier.expects(:notify_new).neverChat::Notifier.expects(:notify_edit).never- subject.execute(- chat_message_id: chat_message.id,- reason: "invalid",- timestamp: 1.minute.ago,- )+ job.execute(chat_message_id: chat_message.id, reason: "invalid", timestamp: 1.minute.ago)endit "does nothing if there is no timestamp" doChat::Notifier.any_instance.expects(:notify_new).neverChat::Notifier.any_instance.expects(:notify_edit).never- subject.execute(chat_message_id: chat_message.id, reason: "new")+ job.execute(chat_message_id: chat_message.id, reason: "new")endit "calls notify_new when the reason is 'new'" doChat::Notifier.any_instance.expects(:notify_new).onceChat::Notifier.any_instance.expects(:notify_edit).never- subject.execute(chat_message_id: chat_message.id, reason: "new", timestamp: 1.minute.ago)+ job.execute(chat_message_id: chat_message.id, reason: "new", timestamp: 1.minute.ago)endit "calls notify_edit when the reason is 'edit'" doChat::Notifier.any_instance.expects(:notify_new).neverChat::Notifier.any_instance.expects(:notify_edit).once- subject.execute(chat_message_id: chat_message.id, reason: "edit", timestamp: 1.minute.ago)+ job.execute(chat_message_id: chat_message.id, reason: "edit", timestamp: 1.minute.ago)endendenddiff --git a/plugins/chat/spec/jobs/scheduled/auto_join_users_spec.rb b/plugins/chat/spec/jobs/scheduled/auto_join_users_spec.rbindex 1807f0e74d5..4abbdc37405 100644--- a/plugins/chat/spec/jobs/scheduled/auto_join_users_spec.rb+++ b/plugins/chat/spec/jobs/scheduled/auto_join_users_spec.rb@@ -3,6 +3,8 @@require "rails_helper"describe Jobs::Chat::AutoJoinUsers do+ subject(:job) { described_class.new }+it "works" doJobs.run_immediately!channel = Fabricate(:category_channel, auto_join_users: true)@@ -11,7 +13,7 @@ describe Jobs::Chat::AutoJoinUsers domembership = Chat::UserChatChannelMembership.find_by(user: user, chat_channel: channel)expect(membership).to be_nil- subject.execute({})+ job.execute({})membership = Chat::UserChatChannelMembership.find_by(user: user, chat_channel: channel)expect(membership.following).to eq(true)diff --git a/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb b/plugins/chat/spec/lib/chat/channel_archive_service_spec.rbindex 8db6a804fc3..1911e2fa3c6 100644--- a/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb+++ b/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb@@ -9,8 +9,8 @@ describe Chat::ChannelArchiveService dofab!(:channel) { Fabricate(:category_channel) }fab!(:user) { Fabricate(:user, admin: true) }fab!(:category) { Fabricate(:category) }+let(:topic_params) { { topic_title: "This will be a new topic", category_id: category.id } }- subject { Chat::ChannelArchiveService }before { SiteSetting.chat_enabled = true }@@ -18,7 +18,7 @@ describe Chat::ChannelArchiveService dobefore { 3.times { Fabricate(:chat_message, chat_channel: channel) } }it "marks the channel as read_only" do- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,@@ -27,7 +27,7 @@ describe Chat::ChannelArchiveService doendit "creates the chat channel archive record to save progress and topic params" do- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,@@ -42,7 +42,7 @@ describe Chat::ChannelArchiveService doit "enqueues the archive job" dochannel_archive =- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,@@ -58,13 +58,13 @@ describe Chat::ChannelArchiveService doendit "does nothing if there is already an archive record for the channel" do- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,)expect {- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,@@ -76,7 +76,7 @@ describe Chat::ChannelArchiveService donew_message = Fabricate(:chat_message, chat_channel: channel)new_message.trash!channel_archive =- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,@@ -92,7 +92,7 @@ describe Chat::ChannelArchiveService dodef start_archive@channel_archive =- subject.create_archive_process(+ described_class.create_archive_process(chat_channel: channel,acting_user: user,topic_params: topic_params,@@ -113,7 +113,7 @@ describe Chat::ChannelArchiveService doemoji: "+1",)stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeend@channel_archive.reload@@ -146,21 +146,21 @@ describe Chat::ChannelArchiveService doit "does not stop the process if the post length is too high (validations disabled)" docreate_messages(50) && start_archiveSiteSetting.max_post_length = 1- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(true)endit "successfully links uploads from messages to the post" docreate_messages(3) && start_archiveUploadReference.create!(target: Chat::Message.last, upload: Fabricate(:upload))- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(true)expect(@channel_archive.destination_topic.posts.last.upload_references.count).to eq(1)endit "successfully sends a private message to the archiving user" docreate_messages(3) && start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(true)pm_topic = Topic.private_messages.lastexpect(pm_topic.topic_allowed_users.first.user).to eq(@channel_archive.archived_by)@@ -174,7 +174,7 @@ describe Chat::ChannelArchiveService docreate_messages(3) && start_archive@channel_archive.update!(destination_topic_title: "Wow this is the new title :tada: :joy:")- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(false)expect(@channel_archive.reload.failed?).to eq(true)expect(@channel_archive.archive_error).to eq("Title can't have more than 1 emoji")@@ -191,7 +191,7 @@ describe Chat::ChannelArchiveService doit "uses the channel slug to autolink a hashtag for the channel in the PM" docreate_messages(3) && start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(true)pm_topic = Topic.private_messages.lastexpect(pm_topic.first_post.cooked).to have_tag(@@ -231,7 +231,7 @@ describe Chat::ChannelArchiveService doChat::UserChatChannelMembership.where(chat_channel: channel, following: true).count,).to eq(3)start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(true)expect(Chat::UserChatChannelMembership.where(chat_channel: channel, following: true).count,@@ -243,7 +243,7 @@ describe Chat::ChannelArchiveService dolast_read_message_id: channel.chat_messages.first.id,)start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeexpect(@channel_archive.reload.complete?).to eq(true)expect(Chat::UserChatChannelMembership.last.last_read_message_id).to eq(channel.chat_messages.last.id,@@ -257,7 +257,7 @@ describe Chat::ChannelArchiveService doit "archives the topic" docreate_messages(3) && start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executetopic = @channel_archive.destination_topictopic.reloadexpect(topic.archived).to eq(true)@@ -269,7 +269,7 @@ describe Chat::ChannelArchiveService doit "leaves the topic open" docreate_messages(3) && start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executetopic = @channel_archive.destination_topictopic.reloadexpect(topic.archived).to eq(false)@@ -282,7 +282,7 @@ describe Chat::ChannelArchiveService doit "closes the topic" docreate_messages(3) && start_archive- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executetopic = @channel_archive.destination_topictopic.reloadexpect(topic.archived).to eq(false)@@ -297,7 +297,7 @@ describe Chat::ChannelArchiveService dodestination_topic_title: nil,destination_topic_id: Fabricate(:topic).id,)- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executetopic = @channel_archive.destination_topictopic.reloadexpect(topic.archived).to eq(false)@@ -322,7 +322,7 @@ describe Chat::ChannelArchiveService doemoji: "+1",)stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeend@channel_archive.reload@@ -363,7 +363,7 @@ describe Chat::ChannelArchiveService do.raises(FakeArchiveError.new("this is a test error"))stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do- expect { subject.new(@channel_archive).execute }.to raise_error(FakeArchiveError)+ expect { described_class.new(@channel_archive).execute }.to raise_error(FakeArchiveError)endexpect(@channel_archive.reload.archive_error).to eq("this is a test error")@@ -376,7 +376,7 @@ describe Chat::ChannelArchiveService doChat::ChannelArchiveService.any_instance.unstub(:create_post)stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do- subject.new(@channel_archive).execute+ described_class.new(@channel_archive).executeend@channel_archive.reloaddiff --git a/plugins/chat/spec/lib/chat/message_bookmarkable_spec.rb b/plugins/chat/spec/lib/chat/message_bookmarkable_spec.rbindex d6c97f1eb59..492ecce8755 100644--- a/plugins/chat/spec/lib/chat/message_bookmarkable_spec.rb+++ b/plugins/chat/spec/lib/chat/message_bookmarkable_spec.rb@@ -3,6 +3,8 @@require "rails_helper"describe Chat::MessageBookmarkable do+ subject(:registered_bookmarkable) { RegisteredBookmarkable.new(described_class) }+fab!(:user) { Fabricate(:user) }fab!(:guardian) { Guardian.new(user) }fab!(:other_category) { Fabricate(:private_category, group: Fabricate(:group)) }@@ -25,23 +27,21 @@ describe Chat::MessageBookmarkable dolet!(:bookmark2) { Fabricate(:bookmark, user: user, bookmarkable: message2) }let!(:bookmark3) { Fabricate(:bookmark) }- subject { RegisteredBookmarkable.new(described_class) }-describe "#perform_list_query" doit "returns all the user's bookmarks" do- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array(+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark1.id, bookmark2.id],)endit "does not return bookmarks for messages inside category chat channels the user cannot access" dochannel.update(chatable: other_category)- expect(subject.perform_list_query(user, guardian)).to eq(nil)+ expect(registered_bookmarkable.perform_list_query(user, guardian)).to eq(nil)other_category.groups.last.add(user)bookmark1.reloaduser.reloadguardian = Guardian.new(user)- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array(+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark1.id, bookmark2.id],)end@@ -49,12 +49,12 @@ describe Chat::MessageBookmarkable doit "does not return bookmarks for messages inside direct message chat channels the user cannot access" dodirect_message = Fabricate(:direct_message)channel.update(chatable: direct_message)- expect(subject.perform_list_query(user, guardian)).to eq(nil)+ expect(registered_bookmarkable.perform_list_query(user, guardian)).to eq(nil)Chat::DirectMessageUser.create(user: user, direct_message: direct_message)bookmark1.reloaduser.reloadguardian = Guardian.new(user)- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array(+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark1.id, bookmark2.id],)end@@ -62,7 +62,9 @@ describe Chat::MessageBookmarkable doit "does not return bookmarks for deleted messages" domessage1.trash!guardian = Guardian.new(user)- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark2.id])+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array(+ [bookmark2.id],+ )endend@@ -72,8 +74,8 @@ describe Chat::MessageBookmarkable doit "returns bookmarks that match by name" dots_query = Search.ts_query(term: "gotta", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%gotta%",ts_query,).map(&:id),@@ -85,8 +87,8 @@ describe Chat::MessageBookmarkable dots_query = Search.ts_query(term: "good soup", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%good soup%",ts_query,).map(&:id),@@ -94,8 +96,8 @@ describe Chat::MessageBookmarkable dots_query = Search.ts_query(term: "blah", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%blah%",ts_query,).map(&:id),@@ -105,23 +107,23 @@ describe Chat::MessageBookmarkable dodescribe "#can_send_reminder?" doit "cannot send the reminder if the message or channel is deleted" do- expect(subject.can_send_reminder?(bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(true)bookmark1.bookmarkable.trash!bookmark1.reload- expect(subject.can_send_reminder?(bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)Chat::Message.with_deleted.find_by(id: bookmark1.bookmarkable_id).recover!bookmark1.reloadbookmark1.bookmarkable.chat_channel.trash!bookmark1.reload- expect(subject.can_send_reminder?(bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)endenddescribe "#reminder_handler" doit "creates a notification for the user with the correct details" do- expect { subject.send_reminder_notification(bookmark1) }.to change { Notification.count }.by(- 1,- )+ expect { registered_bookmarkable.send_reminder_notification(bookmark1) }.to change {+ Notification.count+ }.by(1)notification = user.notifications.lastexpect(notification.notification_type).to eq(Notification.types[:bookmark_reminder])expect(notification.data).to eq(@@ -142,38 +144,44 @@ describe Chat::MessageBookmarkable dodescribe "#can_see?" doit "returns false if the chat message is in a channel the user cannot see" do- expect(subject.can_see?(guardian, bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(true)bookmark1.bookmarkable.chat_channel.update!(chatable: private_category)- expect(subject.can_see?(guardian, bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(false)private_category.groups.last.add(user)bookmark1.reloaduser.reloadguardian = Guardian.new(user)- expect(subject.can_see?(guardian, bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(true)endenddescribe "#validate_before_create" doit "raises InvalidAccess if the user cannot see the chat channel" do- expect { subject.validate_before_create(guardian, bookmark1.bookmarkable) }.not_to raise_error+ expect {+ registered_bookmarkable.validate_before_create(guardian, bookmark1.bookmarkable)+ }.not_to raise_errorbookmark1.bookmarkable.chat_channel.update!(chatable: private_category)- expect { subject.validate_before_create(guardian, bookmark1.bookmarkable) }.to raise_error(- Discourse::InvalidAccess,- )+ expect {+ registered_bookmarkable.validate_before_create(guardian, bookmark1.bookmarkable)+ }.to raise_error(Discourse::InvalidAccess)private_category.groups.last.add(user)bookmark1.reloaduser.reloadguardian = Guardian.new(user)- expect { subject.validate_before_create(guardian, bookmark1.bookmarkable) }.not_to raise_error+ expect {+ registered_bookmarkable.validate_before_create(guardian, bookmark1.bookmarkable)+ }.not_to raise_errorendit "raises InvalidAccess if the chat message is deleted" do- expect { subject.validate_before_create(guardian, bookmark1.bookmarkable) }.not_to raise_error+ expect {+ registered_bookmarkable.validate_before_create(guardian, bookmark1.bookmarkable)+ }.not_to raise_errorbookmark1.bookmarkable.trash!bookmark1.reload- expect { subject.validate_before_create(guardian, bookmark1.bookmarkable) }.to raise_error(- Discourse::InvalidAccess,- )+ expect {+ registered_bookmarkable.validate_before_create(guardian, bookmark1.bookmarkable)+ }.to raise_error(Discourse::InvalidAccess)endend@@ -182,7 +190,7 @@ describe Chat::MessageBookmarkable dobookmark_post = Fabricate(:bookmark, bookmarkable: Fabricate(:post))bookmark1.bookmarkable.trash!bookmark1.bookmarkable.update!(deleted_at: 4.days.ago)- subject.cleanup_deleted+ registered_bookmarkable.cleanup_deletedexpect(Bookmark.exists?(id: bookmark1.id)).to eq(false)expect(Bookmark.exists?(id: bookmark2.id)).to eq(true)expect(Bookmark.exists?(id: bookmark_post.id)).to eq(true)diff --git a/plugins/chat/spec/lib/chat/message_reactor_spec.rb b/plugins/chat/spec/lib/chat/message_reactor_spec.rbindex c6715c3ad16..2a6d3cb06ef 100644--- a/plugins/chat/spec/lib/chat/message_reactor_spec.rb+++ b/plugins/chat/spec/lib/chat/message_reactor_spec.rb@@ -3,39 +3,40 @@require "rails_helper"describe Chat::MessageReactor do+ subject(:message_reactor) { described_class.new(reacting_user, channel) }+fab!(:reacting_user) { Fabricate(:user) }fab!(:channel) { Fabricate(:category_channel) }fab!(:reactor) { described_class.new(reacting_user, channel) }fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel, user: reacting_user) }- let(:subject) { described_class.new(reacting_user, channel) }it "calls guardian ensure_can_join_chat_channel!" doGuardian.any_instance.expects(:ensure_can_join_chat_channel!).once- subject.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")+ message_reactor.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")endit "raises an error if the user cannot see the channel" dochannel.update!(chatable: Fabricate(:private_category, group: Group[:staff]))expect {- subject.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")+ message_reactor.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")}.to raise_error(Discourse::InvalidAccess)endit "raises an error if the user cannot react" doSpamRule::AutoSilence.new(reacting_user).silence_userexpect {- subject.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")+ message_reactor.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")}.to raise_error(Discourse::InvalidAccess)endit "raises an error if the channel status is not open" dochannel.update!(status: Chat::Channel.statuses[:archived])expect {- subject.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")+ message_reactor.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")}.to raise_error(Discourse::InvalidAccess)channel.update!(status: Chat::Channel.statuses[:open])expect {- subject.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")+ message_reactor.react!(message_id: message_1.id, react_action: :add, emoji: ":+1:")}.to change(Chat::MessageReaction, :count).by(1)enddiff --git a/plugins/chat/spec/lib/chat/post_notification_handler_spec.rb b/plugins/chat/spec/lib/chat/post_notification_handler_spec.rbindex 4d7488bc4b7..47705958594 100644--- a/plugins/chat/spec/lib/chat/post_notification_handler_spec.rb+++ b/plugins/chat/spec/lib/chat/post_notification_handler_spec.rb@@ -3,10 +3,11 @@require "rails_helper"describe Chat::PostNotificationHandler do+ subject(:handler) { described_class.new(post, notified_users) }+let(:acting_user) { Fabricate(:user) }let(:post) { Fabricate(:post) }let(:notified_users) { [] }- let(:subject) { described_class.new(post, notified_users) }fab!(:channel) { Fabricate(:category_channel) }fab!(:message1) do@@ -24,7 +25,7 @@ describe Chat::PostNotificationHandler dodef expect_no_notificationreturn_val = nil- expect { return_val = subject.handle }.not_to change { Notification.count }+ expect { return_val = handler.handle }.not_to change { Notification.count }expect(return_val).to eq(false)end@@ -51,7 +52,7 @@ describe Chat::PostNotificationHandler doit "sends notifications to all of the quoted users" doupdate_post_with_chat_quote([message1, message2])- subject.handle+ handler.handleexpect(Notification.where(user: message1.user,@@ -68,8 +69,8 @@ describe Chat::PostNotificationHandler doit "does not send the same chat_quoted notification twice to the same post and user" doupdate_post_with_chat_quote([message1, message2])- subject.handle- subject.handle+ handler.handle+ handler.handleexpect(Notification.where(user: message1.user,@@ -87,7 +88,7 @@ describe Chat::PostNotificationHandler dotopic: post.topic,user: message1.user,)- subject.handle+ handler.handleexpect(Notification.where(user: message1.user,@@ -101,7 +102,7 @@ describe Chat::PostNotificationHandler doit "does not send notifications to those users" doupdate_post_with_chat_quote([message1, message2])- subject.handle+ handler.handleexpect(Notification.where(user: message1.user,diff --git a/plugins/chat/spec/lib/chat/review_queue_spec.rb b/plugins/chat/spec/lib/chat/review_queue_spec.rbindex fb147e7df2e..01b560ac6dd 100644--- a/plugins/chat/spec/lib/chat/review_queue_spec.rb+++ b/plugins/chat/spec/lib/chat/review_queue_spec.rb@@ -3,17 +3,17 @@require "rails_helper"describe Chat::ReviewQueue do+ subject(:queue) { described_class.new }+fab!(:message_poster) { Fabricate(:user) }fab!(:flagger) { Fabricate(:user) }fab!(:chat_channel) { Fabricate(:category_channel) }fab!(:message) { Fabricate(:chat_message, user: message_poster, chat_channel: chat_channel) }-fab!(:admin) { Fabricate(:admin) }+let(:guardian) { Guardian.new(flagger) }let(:admin_guardian) { Guardian.new(admin) }- subject(:queue) { described_class.new }-before dochat_channel.add(message_poster)chat_channel.add(flagger)diff --git a/plugins/chat/spec/models/chat/deleted_chat_user_spec.rb b/plugins/chat/spec/models/chat/deleted_chat_user_spec.rbindex 3d3284728e9..9a1beeaf757 100644--- a/plugins/chat/spec/models/chat/deleted_chat_user_spec.rb+++ b/plugins/chat/spec/models/chat/deleted_chat_user_spec.rb@@ -3,15 +3,19 @@require "rails_helper"describe Chat::DeletedUser do+ subject(:deleted_user) { described_class.new }+describe "#username" doit "returns a default username" do- expect(subject.username).to eq(I18n.t("chat.deleted_chat_username"))+ expect(deleted_user.username).to eq(I18n.t("chat.deleted_chat_username"))endenddescribe "#avatar_template" doit "returns a default path" do- expect(subject.avatar_template).to eq("/plugins/chat/images/deleted-chat-user-avatar.png")+ expect(deleted_user.avatar_template).to eq(+ "/plugins/chat/images/deleted-chat-user-avatar.png",+ )endendenddiff --git a/plugins/chat/spec/queries/chat/channel_unreads_query_spec.rb b/plugins/chat/spec/queries/chat/channel_unreads_query_spec.rbindex 10131b31c8e..112b255c3b7 100644--- a/plugins/chat/spec/queries/chat/channel_unreads_query_spec.rb+++ b/plugins/chat/spec/queries/chat/channel_unreads_query_spec.rb@@ -3,6 +3,15 @@require "rails_helper"describe Chat::ChannelUnreadsQuery do+ subject(:query) do+ described_class.call(+ channel_ids: channel_ids,+ user_id: current_user.id,+ include_missing_memberships: include_missing_memberships,+ include_read: include_read,+ ).map(&:to_h)+ end+fab!(:channel_1) { Fabricate(:category_channel) }fab!(:current_user) { Fabricate(:user) }let(:include_missing_memberships) { false }@@ -15,20 +24,11 @@ describe Chat::ChannelUnreadsQuery dochannel_1.add(current_user)end- let(:subject) do- described_class.call(- channel_ids: channel_ids,- user_id: current_user.id,- include_missing_memberships: include_missing_memberships,- include_read: include_read,- ).map(&:to_h)- end-context "with unread message" dobefore { Fabricate(:chat_message, chat_channel: channel_1) }it "returns a correct unread count" do- expect(subject.first).to eq({ mention_count: 0, unread_count: 1, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 0, unread_count: 1, channel_id: channel_1.id })endcontext "when the membership has been muted" do@@ -40,7 +40,7 @@ describe Chat::ChannelUnreadsQuery doendit "returns a zeroed unread count" do- expect(subject.first).to eq({ mention_count: 0, unread_count: 0, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 0, unread_count: 0, channel_id: channel_1.id })endend@@ -49,13 +49,13 @@ describe Chat::ChannelUnreadsQuery dofab!(:thread) { Fabricate(:chat_thread, channel: channel_1, original_message: thread_om) }it "does include the original message in the unread count" do- expect(subject.first).to eq({ mention_count: 0, unread_count: 2, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 0, unread_count: 2, channel_id: channel_1.id })endit "does not include other thread messages in the unread count" doFabricate(:chat_message, chat_channel: channel_1, thread: thread)Fabricate(:chat_message, chat_channel: channel_1, thread: thread)- expect(subject.first).to eq({ mention_count: 0, unread_count: 2, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 0, unread_count: 2, channel_id: channel_1.id })endend@@ -70,7 +70,7 @@ describe Chat::ChannelUnreadsQuery doendit "returns accurate counts" do- expect(subject).to match_array(+ expect(query).to match_array([{ mention_count: 0, unread_count: 1, channel_id: channel_1.id },{ mention_count: 0, unread_count: 2, channel_id: channel_2.id },@@ -87,7 +87,7 @@ describe Chat::ChannelUnreadsQuery doendit "does not return counts for the channels" do- expect(subject).to match_array(+ expect(query).to match_array([{ mention_count: 0, unread_count: 1, channel_id: channel_1.id }],)end@@ -96,7 +96,7 @@ describe Chat::ChannelUnreadsQuery dolet(:include_missing_memberships) { true }it "does return zeroed counts for the channels" do- expect(subject).to match_array(+ expect(query).to match_array([{ mention_count: 0, unread_count: 1, channel_id: channel_1.id },{ mention_count: 0, unread_count: 0, channel_id: channel_2.id },@@ -108,7 +108,7 @@ describe Chat::ChannelUnreadsQuery dolet(:include_read) { false }it "does not return counts for the channels" do- expect(subject).to match_array(+ expect(query).to match_array([{ mention_count: 0, unread_count: 1, channel_id: channel_1.id }],)end@@ -135,7 +135,7 @@ describe Chat::ChannelUnreadsQuery domessage = Fabricate(:chat_message, chat_channel: channel_1)create_mention(message, channel_1)- expect(subject.first).to eq({ mention_count: 1, unread_count: 1, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 1, unread_count: 1, channel_id: channel_1.id })endcontext "for unread mentions in a thread" do@@ -144,7 +144,7 @@ describe Chat::ChannelUnreadsQuery doit "does include the original message in the mention count" docreate_mention(thread_om, channel_1)- expect(subject.first).to eq({ mention_count: 1, unread_count: 1, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 1, unread_count: 1, channel_id: channel_1.id })endit "does not include other thread messages in the mention count" do@@ -152,7 +152,7 @@ describe Chat::ChannelUnreadsQuery dothread_message_2 = Fabricate(:chat_message, chat_channel: channel_1, thread: thread)create_mention(thread_message_1, channel_1)create_mention(thread_message_2, channel_1)- expect(subject.first).to eq({ mention_count: 0, unread_count: 1, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 0, unread_count: 1, channel_id: channel_1.id })endend@@ -169,7 +169,7 @@ describe Chat::ChannelUnreadsQuery domessage_2 = Fabricate(:chat_message, chat_channel: channel_2)create_mention(message_2, channel_2)- expect(subject).to match_array(+ expect(query).to match_array([{ mention_count: 1, unread_count: 1, channel_id: channel_1.id },{ mention_count: 1, unread_count: 2, channel_id: channel_2.id },@@ -181,14 +181,14 @@ describe Chat::ChannelUnreadsQuery docontext "with nothing unread" doit "returns a correct state" do- expect(subject.first).to eq({ mention_count: 0, unread_count: 0, channel_id: channel_1.id })+ expect(query.first).to eq({ mention_count: 0, unread_count: 0, channel_id: channel_1.id })endcontext "when include_read is false" dolet(:include_read) { false }it "returns nothing" do- expect(subject).to eq([])+ expect(query).to eq([])endendenddiff --git a/plugins/chat/spec/queries/chat/messages_query_spec.rb b/plugins/chat/spec/queries/chat/messages_query_spec.rbindex be46468822e..be6f9a7406b 100644--- a/plugins/chat/spec/queries/chat/messages_query_spec.rb+++ b/plugins/chat/spec/queries/chat/messages_query_spec.rb@@ -1,6 +1,10 @@# frozen_string_literal: trueRSpec.describe Chat::MessagesQuery do+ subject(:query) do+ described_class.call(guardian: current_user.guardian, channel: channel, **options)+ end+fab!(:channel) { Fabricate(:category_channel) }fab!(:current_user) { Fabricate(:user) }@@ -21,10 +25,6 @@ RSpec.describe Chat::MessagesQuery do}end- let(:subject) do- described_class.call(guardian: current_user.guardian, channel: channel, **options)- end-fab!(:message_1) domessage = Fabricate(:chat_message, chat_channel: channel)message.update!(created_at: 2.days.ago)@@ -42,7 +42,7 @@ RSpec.describe Chat::MessagesQuery dolet(:target_message_id) { target_message.id }it "queries messages in the channel and finds the past and future messages" do- expect(subject).to eq(+ expect(query).to eq(past_messages: [message_1],future_messages: [message_3],target_message: target_message,@@ -53,29 +53,29 @@ RSpec.describe Chat::MessagesQuery doit "does not include deleted messages" domessage_3.trash!- expect(subject[:future_messages]).to eq([])+ expect(query[:future_messages]).to eq([])endit "still includes the target message if it is deleted" dotarget_message.trash!- expect(subject[:target_message]).to eq(target_message)+ expect(query[:target_message]).to eq(target_message)endit "can_load_more_past is true when the past messages reach the limit" dostub_const(described_class, "PAST_MESSAGE_LIMIT", 1) do- expect(subject[:can_load_more_past]).to be_truthy+ expect(query[:can_load_more_past]).to be_truthyendendit "can_load_more_future is true when the future messages reach the limit" dostub_const(described_class, "FUTURE_MESSAGE_LIMIT", 1) do- expect(subject[:can_load_more_future]).to be_truthy+ expect(query[:can_load_more_future]).to be_truthyendendit "limits results of paginated query when page_size is not set" dooptions[:target_message_id] = nil- stub_const(described_class, "MAX_PAGE_SIZE", 1) { expect(subject[:messages].length).to eq(1) }+ stub_const(described_class, "MAX_PAGE_SIZE", 1) { expect(query[:messages].length).to eq(1) }enddescribe "when some messages are in threads" do@@ -83,7 +83,7 @@ RSpec.describe Chat::MessagesQuery doit "does not include messages which are thread replies but does include thread original messages" domessage_3.update!(thread: thread)- expect(subject[:future_messages]).to eq([thread.original_message])+ expect(query[:future_messages]).to eq([thread.original_message])endcontext "when include_thread_messages is true" do@@ -94,7 +94,7 @@ RSpec.describe Chat::MessagesQuery dothread: thread,created_at: thread.original_message.created_at + 1.minute,)- expect(subject[:future_messages]).to eq([thread.original_message, message_3])+ expect(query[:future_messages]).to eq([thread.original_message, message_3])endend@@ -105,7 +105,7 @@ RSpec.describe Chat::MessagesQuery dothread: thread,created_at: thread.original_message.created_at + 1.minute,)- expect(subject[:future_messages]).to eq([thread.original_message, message_3])+ expect(query[:future_messages]).to eq([thread.original_message, message_3])endendend@@ -115,7 +115,7 @@ RSpec.describe Chat::MessagesQuery doit "does include deleted messages" domessage_3.trash!- expect(subject[:future_messages]).to eq([message_3])+ expect(query[:future_messages]).to eq([message_3])endendend@@ -124,7 +124,7 @@ RSpec.describe Chat::MessagesQuery dolet(:target_date) { 1.day.ago }it "queries messages in the channel and finds the past and future messages" do- expect(subject).to eq(+ expect(query).to eq(past_messages: [message_1],future_messages: [message_2, message_3],target_date: target_date,@@ -136,7 +136,7 @@ RSpec.describe Chat::MessagesQuery docontext "when target_message_id not provided" doit "queries messages in the channel" do- expect(subject).to eq(+ expect(query).to eq(messages: [message_1, message_2, message_3],can_load_more_past: false,can_load_more_future: false,@@ -147,7 +147,7 @@ RSpec.describe Chat::MessagesQuery dolet(:page_size) { 3 }it "can_load_more_past is true" do- expect(subject[:can_load_more_past]).to be_truthy+ expect(query[:can_load_more_past]).to be_truthyendend@@ -155,14 +155,14 @@ RSpec.describe Chat::MessagesQuery dolet(:direction) { described_class::FUTURE }it "returns messages in ascending order by created_at" do- expect(subject[:messages]).to eq([message_1, message_2, message_3])+ expect(query[:messages]).to eq([message_1, message_2, message_3])endcontext "when the messages length is equal to the page_size" dolet(:page_size) { 3 }it "can_load_more_future is true" do- expect(subject[:can_load_more_future]).to be_truthy+ expect(query[:can_load_more_future]).to be_truthyendendend@@ -171,14 +171,14 @@ RSpec.describe Chat::MessagesQuery dolet(:direction) { described_class::PAST }it "returns messages in ascending order by created_at" do- expect(subject[:messages]).to eq([message_1, message_2, message_3])+ expect(query[:messages]).to eq([message_1, message_2, message_3])endcontext "when the messages length is equal to the page_size" dolet(:page_size) { 3 }it "can_load_more_past is true" do- expect(subject[:can_load_more_past]).to be_truthy+ expect(query[:can_load_more_past]).to be_truthyendendenddiff --git a/plugins/chat/spec/queries/chat/thread_unreads_query_spec.rb b/plugins/chat/spec/queries/chat/thread_unreads_query_spec.rbindex 6b4e83e3f16..2999eef5108 100644--- a/plugins/chat/spec/queries/chat/thread_unreads_query_spec.rb+++ b/plugins/chat/spec/queries/chat/thread_unreads_query_spec.rb@@ -3,6 +3,16 @@require "rails_helper"describe Chat::ThreadUnreadsQuery do+ subject(:query) do+ described_class.call(+ channel_ids: channel_ids,+ thread_ids: thread_ids,+ user_id: current_user.id,+ include_missing_memberships: include_missing_memberships,+ include_read: include_read,+ )+ end+fab!(:channel_1) { Fabricate(:category_channel, threading_enabled: true) }fab!(:channel_2) { Fabricate(:category_channel, threading_enabled: true) }fab!(:thread_1) { Fabricate(:chat_thread, channel: channel_1) }@@ -16,15 +26,6 @@ describe Chat::ThreadUnreadsQuery dolet(:include_read) { true }let(:channel_ids) { [] }let(:thread_ids) { [] }- let(:subject) do- described_class.call(- channel_ids: channel_ids,- thread_ids: thread_ids,- user_id: current_user.id,- include_missing_memberships: include_missing_memberships,- include_read: include_read,- )- endbefore doSiteSetting.chat_enabled = true@@ -47,7 +48,7 @@ describe Chat::ThreadUnreadsQuery dolet(:channel_ids) { [channel_1.id, channel_2.id] }it "gets a count of all the thread unreads across the channels" do- expect(subject.map(&:to_h)).to match_array(+ expect(query.map(&:to_h)).to match_array([{ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 1 },{ channel_id: channel_1.id, mention_count: 0, thread_id: thread_2.id, unread_count: 0 },@@ -59,17 +60,17 @@ describe Chat::ThreadUnreadsQuery doit "does not count deleted messages" domessage_1.trash!- expect(subject.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq(+ expect(query.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 0 },)endit "does not messages in threads where threading_enabled is false on the channel" dochannel_1.update!(threading_enabled: false)- expect(subject.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq(+ expect(query.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 0 },)- expect(subject.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_2.id }).to eq(+ expect(query.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_2.id }).to eq({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_2.id, unread_count: 0 },)end@@ -79,7 +80,7 @@ describe Chat::ThreadUnreadsQuery do.user_chat_thread_memberships.find_by(user: current_user).update!(last_read_message_id: message_1.id)- expect(subject.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq(+ expect(query.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 0 },)end@@ -87,7 +88,7 @@ describe Chat::ThreadUnreadsQuery doit "does not count the original message ID as unread" dothread_1.original_message.destroythread_1.update!(original_message: message_1)- expect(subject.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq(+ expect(query.map(&:to_h).find { |tracking| tracking[:thread_id] == thread_1.id }).to eq({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 0 },)end@@ -96,7 +97,7 @@ describe Chat::ThreadUnreadsQuery dolet(:include_read) { false }it "does not get threads with no unread messages" do- expect(subject.map(&:to_h)).not_to include(+ expect(query.map(&:to_h)).not_to include([{channel_id: channel_1.id,@@ -114,7 +115,7 @@ describe Chat::ThreadUnreadsQuery dolet(:thread_ids) { [thread_1.id, thread_3.id] }it "gets a count of all the thread unreads for the specified threads" do- expect(subject.map(&:to_h)).to match_array(+ expect(query.map(&:to_h)).to match_array([{ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 1 },{ channel_id: channel_2.id, mention_count: 0, thread_id: thread_3.id, unread_count: 1 },@@ -131,7 +132,7 @@ describe Chat::ThreadUnreadsQuery doendit "gets a zeroed out count for the thread" do- expect(subject.map(&:to_h)).to include(+ expect(query.map(&:to_h)).to include({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 0 },)end@@ -146,7 +147,7 @@ describe Chat::ThreadUnreadsQuery doendit "gets a zeroed out count for the thread" do- expect(subject.map(&:to_h)).to include(+ expect(query.map(&:to_h)).to include({ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 0 },)end@@ -156,7 +157,7 @@ describe Chat::ThreadUnreadsQuery dobefore { thread_1.user_chat_thread_memberships.find_by(user: current_user).destroy! }it "does not get that thread unread count by default" do- expect(subject.map(&:to_h)).to match_array(+ expect(query.map(&:to_h)).to match_array([{channel_id: channel_2.id,@@ -172,7 +173,7 @@ describe Chat::ThreadUnreadsQuery dolet(:include_missing_memberships) { true }it "includes the thread that the user is not a member of with zeroed out counts" do- expect(subject.map(&:to_h)).to match_array(+ expect(query.map(&:to_h)).to match_array([{channel_id: channel_1.id,@@ -194,7 +195,7 @@ describe Chat::ThreadUnreadsQuery dolet(:include_read) { false }it "does not include the thread that the user is not a member of with zeroed out counts" do- expect(subject.map(&:to_h)).to match_array(+ expect(query.map(&:to_h)).to match_array([{channel_id: channel_2.id,@@ -215,7 +216,7 @@ describe Chat::ThreadUnreadsQuery dolet(:thread_ids) { [thread_1.id, thread_3.id] }it "gets a count of all the thread unreads across the channels filtered by thread id" do- expect(subject.map(&:to_h)).to match_array(+ expect(query.map(&:to_h)).to match_array([{ channel_id: channel_1.id, mention_count: 0, thread_id: thread_1.id, unread_count: 1 },{ channel_id: channel_2.id, mention_count: 0, thread_id: thread_3.id, unread_count: 1 },diff --git a/plugins/chat/spec/queries/chat/tracking_state_report_query_spec.rb b/plugins/chat/spec/queries/chat/tracking_state_report_query_spec.rbindex 76d7146616c..5a8ad346cef 100644--- a/plugins/chat/spec/queries/chat/tracking_state_report_query_spec.rb+++ b/plugins/chat/spec/queries/chat/tracking_state_report_query_spec.rb@@ -1,15 +1,7 @@# frozen_string_literal: trueRSpec.describe Chat::TrackingStateReportQuery do- fab!(:current_user) { Fabricate(:user) }- let(:guardian) { current_user.guardian }-- let(:channel_ids) { [] }- let(:thread_ids) { [] }- let(:include_missing_memberships) { false }- let(:include_threads) { false }- let(:include_read) { true }- let(:subject) do+ subject(:query) dodescribed_class.call(guardian: guardian,channel_ids: channel_ids,@@ -20,9 +12,17 @@ RSpec.describe Chat::TrackingStateReportQuery do)end+ fab!(:current_user) { Fabricate(:user) }+ let(:guardian) { current_user.guardian }++ let(:channel_ids) { [] }+ let(:thread_ids) { [] }+ let(:include_missing_memberships) { false }+ let(:include_threads) { false }+ let(:include_read) { true }context "when channel_ids empty" doit "returns empty object for channel_tracking" do- expect(subject.channel_tracking).to eq({})+ expect(query.channel_tracking).to eq({})endend@@ -41,7 +41,7 @@ RSpec.describe Chat::TrackingStateReportQuery doinclude_read: include_read,).returns([])- subject+ queryendit "generates a correct unread report for the channels the user is a member of" do@@ -50,7 +50,7 @@ RSpec.describe Chat::TrackingStateReportQuery doFabricate(:chat_message, chat_channel: channel_1)Fabricate(:chat_message, chat_channel: channel_2)- expect(subject.channel_tracking).to eq(+ expect(query.channel_tracking).to eq({channel_1.id => {unread_count: 1,@@ -66,7 +66,7 @@ RSpec.describe Chat::TrackingStateReportQuery doit "does not include threads by default" doChat::ThreadUnreadsQuery.expects(:call).never- expect(subject.thread_tracking).to eq({})+ expect(query.thread_tracking).to eq({})endcontext "when include_threads is true" do@@ -90,7 +90,7 @@ RSpec.describe Chat::TrackingStateReportQuery doinclude_read: include_read,).returns([])- subject+ queryendit "generates a correct unread for the threads the user is a member of in the channels" do@@ -101,7 +101,7 @@ RSpec.describe Chat::TrackingStateReportQuery doFabricate(:chat_message, chat_channel: channel_1, thread: thread_1)Fabricate(:chat_message, chat_channel: channel_2, thread: thread_2)- expect(subject.channel_tracking).to eq(+ expect(query.channel_tracking).to eq({channel_1.id => {unread_count: 1,@@ -113,7 +113,7 @@ RSpec.describe Chat::TrackingStateReportQuery do},},)- expect(subject.thread_tracking).to eq(+ expect(query.thread_tracking).to eq({thread_1.id => {unread_count: 1,@@ -135,7 +135,7 @@ RSpec.describe Chat::TrackingStateReportQuery doit "does not query threads" doChat::ThreadUnreadsQuery.expects(:call).never- expect(subject.thread_tracking).to eq({})+ expect(query.thread_tracking).to eq({})endendenddiff --git a/plugins/chat/spec/serializer/chat/channel_serializer_spec.rb b/plugins/chat/spec/serializer/chat/channel_serializer_spec.rbindex b8c4e9c52b8..8a4160ff9cd 100644--- a/plugins/chat/spec/serializer/chat/channel_serializer_spec.rb+++ b/plugins/chat/spec/serializer/chat/channel_serializer_spec.rb@@ -3,23 +3,25 @@require "rails_helper"describe Chat::ChannelSerializer do+ subject(:serializer) { described_class.new(chat_channel, scope: guardian, root: nil) }+fab!(:user) { Fabricate(:user) }fab!(:admin) { Fabricate(:admin) }fab!(:chat_channel) { Fabricate(:chat_channel) }+let(:guardian_user) { user }let(:guardian) { Guardian.new(guardian_user) }- subject { described_class.new(chat_channel, scope: guardian, root: nil) }describe "archive status" docontext "when user is not staff" dolet(:guardian_user) { user }it "does not return any sort of archive status" do- expect(subject.as_json.key?(:archive_completed)).to eq(false)+ expect(serializer.as_json.key?(:archive_completed)).to eq(false)endit "includes allow_channel_wide_mentions" do- expect(subject.as_json.key?(:allow_channel_wide_mentions)).to eq(true)+ expect(serializer.as_json.key?(:allow_channel_wide_mentions)).to eq(true)endend@@ -27,10 +29,10 @@ describe Chat::ChannelSerializer dolet(:guardian_user) { admin }it "includes the archive status if the channel is archived and the archive record exists" do- expect(subject.as_json.key?(:archive_completed)).to eq(false)+ expect(serializer.as_json.key?(:archive_completed)).to eq(false)chat_channel.update!(status: Chat::Channel.statuses[:archived])- expect(subject.as_json.key?(:archive_completed)).to eq(false)+ expect(serializer.as_json.key?(:archive_completed)).to eq(false)Chat::ChannelArchive.create!(chat_channel: chat_channel,@@ -39,11 +41,11 @@ describe Chat::ChannelSerializer dototal_messages: 10,)chat_channel.reload- expect(subject.as_json.key?(:archive_completed)).to eq(true)+ expect(serializer.as_json.key?(:archive_completed)).to eq(true)endit "includes allow_channel_wide_mentions" do- expect(subject.as_json.key?(:allow_channel_wide_mentions)).to eq(true)+ expect(serializer.as_json.key?(:allow_channel_wide_mentions)).to eq(true)endendend@@ -63,7 +65,7 @@ describe Chat::ChannelSerializer doMessageBus.expects(:last_id).with(Chat::Publisher.kick_users_message_bus_channel(chat_channel.id),)- expect(subject.as_json.dig(:meta, :message_bus_last_ids).keys).to eq(+ expect(serializer.as_json.dig(:meta, :message_bus_last_ids).keys).to eq(%i[channel_message_bus_last_id new_messages new_mentions kick],)end@@ -73,7 +75,7 @@ describe Chat::ChannelSerializer doMessageBus.expects(:last_id).with(Chat::Publisher.kick_users_message_bus_channel(chat_channel.id),)- expect(subject.as_json[:meta][:message_bus_last_ids].key?(:kick)).to eq(true)+ expect(serializer.as_json[:meta][:message_bus_last_ids].key?(:kick)).to eq(true)endit "does not call MessageBus for last_id if all the last IDs are already passed in" do@@ -101,7 +103,7 @@ describe Chat::ChannelSerializer doMessageBus.expects(:last_id).with(Chat::Publisher.new_mentions_message_bus_channel(chat_channel.id),)- expect(subject.as_json.dig(:meta, :message_bus_last_ids).keys).to eq(+ expect(serializer.as_json.dig(:meta, :message_bus_last_ids).keys).to eq(%i[channel_message_bus_last_id new_messages new_mentions],)end@@ -109,7 +111,7 @@ describe Chat::ChannelSerializer doit "does not get the kick_message_bus_last_id" doMessageBus.expects(:last_id).at_least_onceMessageBus.expects(:last_id).never- expect(subject.as_json[:meta][:message_bus_last_ids].key?(:kick)).to eq(false)+ expect(serializer.as_json[:meta][:message_bus_last_ids].key?(:kick)).to eq(false)endendenddiff --git a/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rb b/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rbindex 9f1218b0618..89abcb42bc9 100644--- a/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rb+++ b/plugins/chat/spec/serializer/chat/chat_message_serializer_spec.rb@@ -3,13 +3,14 @@require "rails_helper"describe Chat::MessageSerializer do+ subject(:serializer) { described_class.new(message_1, scope: guardian, root: nil) }+fab!(:chat_channel) { Fabricate(:category_channel) }fab!(:message_poster) { Fabricate(:user) }fab!(:message_1) { Fabricate(:chat_message, user: message_poster, chat_channel: chat_channel) }fab!(:guardian_user) { Fabricate(:user) }- let(:guardian) { Guardian.new(guardian_user) }- subject { described_class.new(message_1, scope: guardian, root: nil) }+ let(:guardian) { Guardian.new(guardian_user) }describe "#reactions" dofab!(:custom_emoji) { CustomEmoji.create!(name: "trout", upload: Fabricate(:upload)) }@@ -21,13 +22,13 @@ describe Chat::MessageSerializer doit "doesn’t return the reaction" doEmoji.clear_cache- trout_reaction = subject.as_json[:reactions].find { |r| r[:emoji] == "trout" }+ trout_reaction = serializer.as_json[:reactions].find { |r| r[:emoji] == "trout" }expect(trout_reaction).to be_presentcustom_emoji.destroy!Emoji.clear_cache- trout_reaction = subject.as_json[:reactions].find { |r| r[:emoji] == "trout" }+ trout_reaction = serializer.as_json[:reactions].find { |r| r[:emoji] == "trout" }expect(trout_reaction).to_not be_presentendend@@ -49,7 +50,7 @@ describe Chat::MessageSerializer domessage_1.user.destroy!message_1.reload- expect(subject.as_json[:user][:username]).to eq(I18n.t("chat.deleted_chat_username"))+ expect(serializer.as_json[:user][:username]).to eq(I18n.t("chat.deleted_chat_username"))endendend@@ -60,14 +61,14 @@ describe Chat::MessageSerializer domessage_1.user.destroy!message_1.reload- expect(subject.as_json[:deleted_at]).to(be_within(1.second).of(Time.zone.now))+ expect(serializer.as_json[:deleted_at]).to(be_within(1.second).of(Time.zone.now))endit "is marked as deleted by system user" domessage_1.user.destroy!message_1.reload- expect(subject.as_json[:deleted_by_id]).to eq(Discourse.system_user.id)+ expect(serializer.as_json[:deleted_by_id]).to eq(Discourse.system_user.id)endendenddiff --git a/plugins/chat/spec/serializer/chat/chat_message_user_serializer_spec.rb b/plugins/chat/spec/serializer/chat/chat_message_user_serializer_spec.rbindex 94c63dceca6..fa12515bc2b 100644--- a/plugins/chat/spec/serializer/chat/chat_message_user_serializer_spec.rb+++ b/plugins/chat/spec/serializer/chat/chat_message_user_serializer_spec.rb@@ -3,7 +3,7 @@require "rails_helper"RSpec.describe Chat::MessageUserSerializer do- subject do+ subject(:serializer) douser = Fabricate(:user, **params)guardian = Guardian.new(user)described_class.new(user, scope: guardian, root: nil).as_json@@ -15,11 +15,11 @@ RSpec.describe Chat::MessageUserSerializer docontext "with default user" doit "displays user as regular" do- expect(subject[:new_user]).to eq(false)- expect(subject[:staff]).to eq(false)- expect(subject[:admin]).to eq(false)- expect(subject[:moderator]).to eq(false)- expect(subject[:primary_group_name]).to be_blank+ expect(serializer[:new_user]).to eq(false)+ expect(serializer[:staff]).to eq(false)+ expect(serializer[:admin]).to eq(false)+ expect(serializer[:moderator]).to eq(false)+ expect(serializer[:primary_group_name]).to be_blankendend@@ -27,7 +27,7 @@ RSpec.describe Chat::MessageUserSerializer dobefore { params[:trust_level] = TrustLevel[0] }it "displays user as new" do- expect(subject[:new_user]).to eq(true)+ expect(serializer[:new_user]).to eq(true)endend@@ -35,7 +35,7 @@ RSpec.describe Chat::MessageUserSerializer dobefore { params[:admin] = true }it "displays user as staff" do- expect(subject[:staff]).to eq(true)+ expect(serializer[:staff]).to eq(true)endend@@ -43,7 +43,7 @@ RSpec.describe Chat::MessageUserSerializer dobefore { params[:admin] = true }it "displays user as admin" do- expect(subject[:admin]).to eq(true)+ expect(serializer[:admin]).to eq(true)endend@@ -51,7 +51,7 @@ RSpec.describe Chat::MessageUserSerializer dobefore { params[:moderator] = true }it "displays user as moderator" do- expect(subject[:moderator]).to eq(true)+ expect(serializer[:moderator]).to eq(true)endend@@ -61,7 +61,7 @@ RSpec.describe Chat::MessageUserSerializer dobefore { params[:primary_group_id] = group.id }it "displays user as moderator" do- expect(subject[:primary_group_name]).to eq(group.name)+ expect(serializer[:primary_group_name]).to eq(group.name)endendenddiff --git a/plugins/chat/spec/services/chat/channel_view_builder_spec.rb b/plugins/chat/spec/services/chat/channel_view_builder_spec.rbindex 99a9eb9e917..9717346cd94 100644--- a/plugins/chat/spec/services/chat/channel_view_builder_spec.rb+++ b/plugins/chat/spec/services/chat/channel_view_builder_spec.rb@@ -11,6 +11,8 @@ RSpec.describe Chat::ChannelViewBuilder doenddescribe ".call" do+ subject(:result) { described_class.call(params) }+fab!(:current_user) { Fabricate(:user) }fab!(:channel) { Fabricate(:category_channel) }@@ -35,14 +37,12 @@ RSpec.describe Chat::ChannelViewBuilder do}end- subject(:result) { described_class.call(params) }-it "threads_enabled is false by default" do- expect(subject.threads_enabled).to eq(false)+ expect(result.threads_enabled).to eq(false)endit "include_thread_messages is true by default" do- expect(subject.include_thread_messages).to eq(true)+ expect(result.include_thread_messages).to eq(true)endit "queries messages" do@@ -59,7 +59,7 @@ RSpec.describe Chat::ChannelViewBuilder dotarget_date: target_date,).returns({ messages: [] })- subject+ resultendit "returns channel messages and thread replies" do@@ -71,23 +71,23 @@ RSpec.describe Chat::ChannelViewBuilder dochat_channel: channel,thread: Fabricate(:chat_thread, channel: channel),)- expect(subject.view.chat_messages).to eq(+ expect(result.view.chat_messages).to eq([message_1, message_2, message_3.thread.original_message, message_3],)endit "does not query thread tracking overview or state by default" doChat::TrackingStateReportQuery.expects(:call).never- subject+ resultendit "does not query threads by default" doChat::Thread.expects(:where).never- subject+ resultendit "returns a Chat::View" do- expect(subject.view).to be_a(Chat::View)+ expect(result.view).to be_a(Chat::View)endcontext "when page_size is null" do@@ -109,11 +109,11 @@ RSpec.describe Chat::ChannelViewBuilder doendit "threads_enabled is true" do- expect(subject.threads_enabled).to eq(true)+ expect(result.threads_enabled).to eq(true)endit "include_thread_messages is false" do- expect(subject.include_thread_messages).to eq(false)+ expect(result.include_thread_messages).to eq(false)endit "returns channel messages but not thread replies" do@@ -125,7 +125,7 @@ RSpec.describe Chat::ChannelViewBuilder dochat_channel: channel,thread: Fabricate(:chat_thread, channel: channel),)- expect(subject.view.chat_messages).to eq(+ expect(result.view.chat_messages).to eq([message_1, message_2, message_3.thread.original_message],)end@@ -137,7 +137,7 @@ RSpec.describe Chat::ChannelViewBuilder dochat_channel: channel,thread: Fabricate(:chat_thread, channel: channel),)- expect(subject.view.threads).to eq([message_1.thread])+ expect(result.view.threads).to eq([message_1.thread])endit "fetches thread memberships for the current user for fetched threads" do@@ -148,7 +148,7 @@ RSpec.describe Chat::ChannelViewBuilder dothread: Fabricate(:chat_thread, channel: channel),)message_1.thread.add(current_user)- expect(subject.view.thread_memberships).to eq(+ expect(result.view.thread_memberships).to eq([message_1.thread.membership_for(current_user)],)end@@ -171,21 +171,21 @@ RSpec.describe Chat::ChannelViewBuilder do.with(guardian: guardian, thread_ids: [thread.id], include_threads: true).returns(Chat::TrackingStateReport.new).once- subject+ resultendit "fetches an overview of threads with unread messages in the channel" dothread = Fabricate(:chat_thread, channel: channel)thread.add(current_user)message_1 = Fabricate(:chat_message, chat_channel: channel, thread: thread)- expect(subject.view.unread_thread_ids).to eq([message_1.thread.id])+ expect(result.view.unread_thread_ids).to eq([message_1.thread.id])endit "fetches the tracking state of threads in the channel" dothread = Fabricate(:chat_thread, channel: channel)thread.add(current_user)Fabricate(:chat_message, chat_channel: channel, thread: thread)- expect(subject.view.tracking.thread_tracking).to eq(+ expect(result.view.tracking.thread_tracking).to eq({ thread.id => { channel_id: channel.id, unread_count: 1, mention_count: 0 } },)end@@ -194,7 +194,7 @@ RSpec.describe Chat::ChannelViewBuilder dolet(:thread_id) { Fabricate(:chat_thread, channel: channel).id }it "include_thread_messages is true" do- expect(subject.include_thread_messages).to eq(true)+ expect(result.include_thread_messages).to eq(true)endendend@@ -233,7 +233,7 @@ RSpec.describe Chat::ChannelViewBuilder docontext "if the user is not a member of the channel" doit "does not error and still returns messages" do- expect(subject.view.chat_messages).to eq([past_message_2, past_message_1, message])+ expect(result.view.chat_messages).to eq([past_message_2, past_message_1, message])endend@@ -246,7 +246,7 @@ RSpec.describe Chat::ChannelViewBuilder dobefore { membership.update!(last_read_message_id: past_message_1.id) }it "uses the last_read_message_id of the user's membership as the target_message_id" do- expect(subject.view.chat_messages).to eq([past_message_2, past_message_1, message])+ expect(result.view.chat_messages).to eq([past_message_2, past_message_1, message])endend@@ -254,7 +254,7 @@ RSpec.describe Chat::ChannelViewBuilder dobefore { membership.update!(last_read_message_id: nil) }it "does not error and still returns messages" do- expect(subject.view.chat_messages).to eq([past_message_2, past_message_1, message])+ expect(result.view.chat_messages).to eq([past_message_2, past_message_1, message])endcontext "if page_size is nil" do@@ -266,7 +266,7 @@ RSpec.describe Chat::ChannelViewBuilder do.with(has_entries(page_size: Chat::MessagesQuery::MAX_PAGE_SIZE)).once.returns({ messages: [] })- subject+ resultendendend@@ -288,7 +288,7 @@ RSpec.describe Chat::ChannelViewBuilder dolet(:target_message_id) { message.id }it "includes the target message as well as past and future messages" do- expect(subject.view.chat_messages).to eq([past_message, message, future_message])+ expect(result.view.chat_messages).to eq([past_message, message, future_message])endcontext "when page_size is null" do@@ -303,7 +303,7 @@ RSpec.describe Chat::ChannelViewBuilder dobefore { message.update!(thread: thread) }it "includes it by default" do- expect(subject.view.chat_messages).to eq(+ expect(result.view.chat_messages).to eq([past_message, message, thread.original_message, future_message],)end@@ -315,7 +315,7 @@ RSpec.describe Chat::ChannelViewBuilder doendit "does not include the target message" do- expect(subject.view.chat_messages).to eq(+ expect(result.view.chat_messages).to eq([past_message, thread.original_message, future_message],)end@@ -356,7 +356,7 @@ RSpec.describe Chat::ChannelViewBuilder dolet(:target_date) { 2.days.ago }it "includes past and future messages" do- expect(subject.view.chat_messages).to eq([past_message, future_message])+ expect(result.view.chat_messages).to eq([past_message, future_message])endendenddiff --git a/plugins/poll/spec/lib/polls_validator_spec.rb b/plugins/poll/spec/lib/polls_validator_spec.rbindex 583a96c80e7..e337db78003 100644--- a/plugins/poll/spec/lib/polls_validator_spec.rb+++ b/plugins/poll/spec/lib/polls_validator_spec.rb@@ -3,8 +3,9 @@require "rails_helper"RSpec.describe ::DiscoursePoll::PollsValidator do+ subject(:validator) { described_class.new(post) }+let(:post) { Fabricate(:post) }- subject { described_class.new(post) }describe "#validate_polls" doit "ensures that polls have valid arguments" dodiff --git a/spec/integration/email_style_spec.rb b/spec/integration/email_style_spec.rbindex 1b6aa37a7da..645ed98a70e 100644--- a/spec/integration/email_style_spec.rb+++ b/spec/integration/email_style_spec.rb@@ -23,10 +23,11 @@ RSpec.describe EmailStyle doendcontext "with invite" do+ subject(:mail_html) { Email::Renderer.new(invite_mail).html }+fab!(:invite) { Fabricate(:invite) }- let(:invite_mail) { InviteMailer.send_invite(invite) }- subject(:mail_html) { Email::Renderer.new(invite_mail).html }+ let(:invite_mail) { InviteMailer.send_invite(invite) }it "applies customizations" doexpect(mail_html.scan('<h1 style="color: red;">FOR YOU</h1>').count).to eq(1)@@ -48,6 +49,8 @@ RSpec.describe EmailStyle doendcontext "when user_replied" do+ subject(:mail_html) { Email::Renderer.new(mail).html }+let(:response_by_user) { Fabricate(:user, name: "John Doe") }let(:category) { Fabricate(:category, name: "India") }let(:topic) { Fabricate(:topic, category: category, title: "Super cool topic") }@@ -65,8 +68,6 @@ RSpec.describe EmailStyle do)end- subject(:mail_html) { Email::Renderer.new(mail).html }-it "customizations are applied to html part of emails" doSiteSetting.default_email_in_reply_to = true@@ -80,9 +81,10 @@ RSpec.describe EmailStyle doendcontext "with signup" do- let(:signup_mail) { UserNotifications.signup(Fabricate(:user)) }subject(:mail_html) { Email::Renderer.new(signup_mail).html }+ let(:signup_mail) { UserNotifications.signup(Fabricate(:user)) }+it "customizations are applied to html part of emails" doexpect(mail_html.scan('<h1 style="color: red;">FOR YOU</h1>').count).to eq(1)expect(mail_html).to include("activate-account")@@ -124,11 +126,13 @@ RSpec.describe EmailStyle doendcontext "with digest" do+ subject(:mail_html) { Email::Renderer.new(summary_email).html }+fab!(:popular_topic) doFabricate(:topic, user: Fabricate(:coding_horror), created_at: 1.hour.ago)end+let(:summary_email) { UserNotifications.digest(Fabricate(:user)) }- subject(:mail_html) { Email::Renderer.new(summary_email).html }it "customizations are applied to html part of emails" doexpect(mail_html.scan('<h1 style="color: red;">FOR YOU</h1>').count).to eq(1)diff --git a/spec/jobs/auto_queue_handler_spec.rb b/spec/jobs/auto_queue_handler_spec.rbindex f4d1ada3afc..718234c9435 100644--- a/spec/jobs/auto_queue_handler_spec.rb+++ b/spec/jobs/auto_queue_handler_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe Jobs::AutoQueueHandler do- subject { Jobs::AutoQueueHandler.new.execute({}) }+ subject(:job) { Jobs::AutoQueueHandler.new.execute({}) }describe "old flagged post" dofab!(:spam_result) do@@ -23,7 +23,7 @@ RSpec.describe Jobs::AutoQueueHandler doit "defers the old flag if auto_handle_queued_age is 60" doSiteSetting.auto_handle_queued_age = 60- subject+ jobexpect(not_old.reload).to be_pendingexpect(old.reload).not_to be_pendingexpect(post_action.related_post.topic.posts_count).to eq(1)@@ -31,7 +31,7 @@ RSpec.describe Jobs::AutoQueueHandler doit "doesn't defer the old flag if auto_handle_queued_age is 0" doSiteSetting.auto_handle_queued_age = 0- subject+ jobexpect(not_old.reload).to be_pendingexpect(old.reload).to be_pendingend@@ -45,7 +45,7 @@ RSpec.describe Jobs::AutoQueueHandler doit "rejects the post when auto_handle_queued_age is 60" doSiteSetting.auto_handle_queued_age = 60- subject+ jobexpect(new_post.reload.pending?).to eq(true)expect(old_post.reload.rejected?).to eq(true)expect(new_user.reload.pending?).to eq(true)@@ -54,7 +54,7 @@ RSpec.describe Jobs::AutoQueueHandler doit "leaves reviewables as pending auto_handle_queued_age is 0" doSiteSetting.auto_handle_queued_age = 0- subject+ jobexpect(new_post.reload.pending?).to eq(true)expect(new_user.reload.pending?).to eq(true)expect(old_post.reload.pending?).to eq(true)diff --git a/spec/jobs/bookmark_reminder_notifications_spec.rb b/spec/jobs/bookmark_reminder_notifications_spec.rbindex 22a9a17f83b..eb6b256da97 100644--- a/spec/jobs/bookmark_reminder_notifications_spec.rb+++ b/spec/jobs/bookmark_reminder_notifications_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe Jobs::BookmarkReminderNotifications do- subject { described_class.new }+ subject(:job) { described_class.new }fab!(:user) { Fabricate(:user) }let(:five_minutes_ago) { Time.zone.now - 5.minutes }@@ -19,7 +19,7 @@ RSpec.describe Jobs::BookmarkReminderNotifications doendit "sends every reminder and sets the reminder_last_sent_at" do- subject.execute+ job.executebookmark1.reloadbookmark2.reloadbookmark3.reload@@ -31,7 +31,7 @@ RSpec.describe Jobs::BookmarkReminderNotifications doit "will not send a reminder for a bookmark in the future" dofreeze_timebookmark4 = Fabricate(:bookmark, reminder_at: Time.zone.now + 1.day)- expect { subject.execute }.to change { Notification.where(user: user).count }.by(3)+ expect { job.execute }.to change { Notification.where(user: user).count }.by(3)expect(bookmark1.reload.reminder_last_sent_at).to eq_time(Time.zone.now)expect(bookmark2.reload.reminder_last_sent_at).to eq_time(Time.zone.now)expect(bookmark3.reload.reminder_last_sent_at).to eq_time(Time.zone.now)@@ -44,7 +44,7 @@ RSpec.describe Jobs::BookmarkReminderNotifications doother_bookmark = Fabricate(:bookmark, user: bookmark1.user)other_bookmark.update_column(:reminder_at, five_minutes_ago)SiteSetting.max_bookmarks_per_user = 2- expect { subject.execute }.not_to raise_error+ expect { job.execute }.not_to raise_errorendend@@ -52,7 +52,7 @@ RSpec.describe Jobs::BookmarkReminderNotifications doit "does not send them in the current run, but will send them in the next" dobeginJobs::BookmarkReminderNotifications.max_reminder_notifications_per_run = 2- subject.execute+ job.executeexpect(bookmark1.reload.reminder_last_sent_at).not_to eq(nil)expect(bookmark2.reload.reminder_last_sent_at).not_to eq(nil)expect(bookmark3.reload.reminder_last_sent_at).to eq(nil)@@ -64,7 +64,7 @@ RSpec.describe Jobs::BookmarkReminderNotifications dobookmark1.bookmarkable.topic.destroybookmark2.bookmarkable.topic.destroybookmark3.bookmarkable.topic.destroy- expect { subject.execute }.not_to change {+ expect { job.execute }.not_to change {Notification.where(notification_type: Notification.types[:bookmark_reminder]).count}enddiff --git a/spec/jobs/clean_up_associated_accounts_spec.rb b/spec/jobs/clean_up_associated_accounts_spec.rbindex cefcac82bde..b9ecb71e837 100644--- a/spec/jobs/clean_up_associated_accounts_spec.rb+++ b/spec/jobs/clean_up_associated_accounts_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe Jobs::CleanUpAssociatedAccounts do- subject { Jobs::CleanUpAssociatedAccounts.new.execute({}) }+ subject(:job) { Jobs::CleanUpAssociatedAccounts.new.execute({}) }it "deletes the correct records" dofreeze_time@@ -26,7 +26,7 @@ RSpec.describe Jobs::CleanUpAssociatedAccounts doupdated_at: 12.hours.ago,)- expect { subject }.to change { UserAssociatedAccount.count }.by(-1)+ expect { job }.to change { UserAssociatedAccount.count }.by(-1)expect(UserAssociatedAccount.all).to contain_exactly(today, connected)endenddiff --git a/spec/jobs/clean_up_crawler_stats_spec.rb b/spec/jobs/clean_up_crawler_stats_spec.rbindex 8f954b4334d..0b51f1683ed 100644--- a/spec/jobs/clean_up_crawler_stats_spec.rb+++ b/spec/jobs/clean_up_crawler_stats_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe Jobs::CleanUpCrawlerStats do- subject { Jobs::CleanUpCrawlerStats.new.execute({}) }+ subject(:job) { Jobs::CleanUpCrawlerStats.new.execute({}) }it "deletes records older than 30 days old" dofreeze_time@@ -10,7 +10,7 @@ RSpec.describe Jobs::CleanUpCrawlerStats doyesterday = Fabricate(:web_crawler_request, date: 1.day.ago.to_date)too_old = Fabricate(:web_crawler_request, date: 31.days.ago.to_date)- expect { subject }.to change { WebCrawlerRequest.count }.by(-1)+ expect { job }.to change { WebCrawlerRequest.count }.by(-1)expect(WebCrawlerRequest.where(id: too_old.id)).to_not existend@@ -25,7 +25,7 @@ RSpec.describe Jobs::CleanUpCrawlerStats doreq2 = Fabricate(:web_crawler_request, date: 1.day.ago.to_date, count: 50)req5 = Fabricate(:web_crawler_request, date: 1.day.ago.to_date, count: 1)- expect { subject }.to change { WebCrawlerRequest.count }.by(-2)+ expect { job }.to change { WebCrawlerRequest.count }.by(-2)expect(WebCrawlerRequest.all).to contain_exactly(req1, req2, req3)endenddiff --git a/spec/jobs/create_recent_post_search_indexes_spec.rb b/spec/jobs/create_recent_post_search_indexes_spec.rbindex 5c5f85dfda3..67a4de9fcc2 100644--- a/spec/jobs/create_recent_post_search_indexes_spec.rb+++ b/spec/jobs/create_recent_post_search_indexes_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe Jobs::CreateRecentPostSearchIndexes do- subject { described_class.new }+ subject(:job) { described_class.new }fab!(:post) { with_search_indexer_enabled { Fabricate(:post) } }fab!(:post_2) { with_search_indexer_enabled { Fabricate(:post) } }@@ -13,7 +13,7 @@ RSpec.describe Jobs::CreateRecentPostSearchIndexes doSiteSetting.search_recent_posts_size = 1SiteSetting.search_enable_recent_regular_posts_offset_size = 3- expect do subject.execute({}) end.to_not change {+ expect { job.execute({}) }.to_not change {SiteSetting.search_recent_regular_posts_offset_post_id}end@@ -22,7 +22,7 @@ RSpec.describe Jobs::CreateRecentPostSearchIndexes doSiteSetting.search_recent_posts_size = 1SiteSetting.search_enable_recent_regular_posts_offset_size = 1- subject.execute({})+ job.execute({})expect(SiteSetting.search_recent_regular_posts_offset_post_id).to eq(post_2.id)diff --git a/spec/jobs/emit_web_hook_event_spec.rb b/spec/jobs/emit_web_hook_event_spec.rbindex efddb33a040..38d024ba94b 100644--- a/spec/jobs/emit_web_hook_event_spec.rb+++ b/spec/jobs/emit_web_hook_event_spec.rb@@ -3,25 +3,27 @@require "excon"RSpec.describe Jobs::EmitWebHookEvent do+ subject(:job) { described_class.new }+fab!(:post_hook) { Fabricate(:web_hook) }fab!(:inactive_hook) { Fabricate(:inactive_web_hook) }fab!(:post) { Fabricate(:post) }fab!(:user) { Fabricate(:user) }it "raises an error when there is no web hook record" do- expect do subject.execute(event_type: "post", payload: {}) end.to raise_error(+ expect { job.execute(event_type: "post", payload: {}) }.to raise_error(Discourse::InvalidParameters,)endit "raises an error when there is no event type" do- expect do subject.execute(web_hook_id: post_hook.id, payload: {}) end.to raise_error(+ expect { job.execute(web_hook_id: post_hook.id, payload: {}) }.to raise_error(Discourse::InvalidParameters,)endit "raises an error when there is no payload" do- expect do subject.execute(web_hook_id: post_hook.id, event_type: "post") end.to raise_error(+ expect { job.execute(web_hook_id: post_hook.id, event_type: "post") }.to raise_error(Discourse::InvalidParameters,)end@@ -29,7 +31,7 @@ RSpec.describe Jobs::EmitWebHookEvent doit "should not destroy webhook event in case of error" dostub_request(:post, post_hook.payload_url).to_return(status: 500)- subject.execute(+ job.execute(web_hook_id: post_hook.id,payload: { id: post.id }.to_json,event_type: WebHookEventType::POST,@@ -53,7 +55,7 @@ RSpec.describe Jobs::EmitWebHookEvent doit "disables the webhook" doexpect do- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: described_class::PING_EVENT,retry_count: described_class::MAX_RETRY_COUNT,@@ -62,7 +64,7 @@ RSpec.describe Jobs::EmitWebHookEvent doendit "logs webhook deactivation reason" do- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: described_class::PING_EVENT,retry_count: described_class::MAX_RETRY_COUNT,@@ -86,7 +88,7 @@ RSpec.describe Jobs::EmitWebHookEvent doit "retry if site setting is enabled" doexpect do- subject.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)+ job.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)end.to change { Jobs::EmitWebHookEvent.jobs.size }.by(1)end@@ -96,13 +98,13 @@ RSpec.describe Jobs::EmitWebHookEvent doexpect(Jobs::EmitWebHookEvent::MAX_RETRY_COUNT + 1).to eq(5)expect do- subject.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)+ job.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)end.to change { WebHookEvent.count }.by(Jobs::EmitWebHookEvent::MAX_RETRY_COUNT + 1)endit "does not retry for more than maximum allowed times" doexpect do- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: described_class::PING_EVENT,retry_count: described_class::MAX_RETRY_COUNT,@@ -114,13 +116,13 @@ RSpec.describe Jobs::EmitWebHookEvent doSiteSetting.retry_web_hook_events = falseexpect do- subject.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)+ job.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)end.not_to change { Jobs::EmitWebHookEvent.jobs.size }endit "properly logs error on rescue" dostub_request(:post, post_hook.payload_url).to_raise("connection error")- subject.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)+ job.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)event = WebHookEvent.lastexpect(event.payload).to eq(MultiJson.dump(ping: "OK"))@@ -133,11 +135,11 @@ RSpec.describe Jobs::EmitWebHookEvent doit "does not raise an error for a ping event without payload" dostub_request(:post, post_hook.payload_url).to_return(body: "OK", status: 200)- subject.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)+ job.execute(web_hook_id: post_hook.id, event_type: described_class::PING_EVENT)endit "doesn't emit when the hook is inactive" do- subject.execute(+ job.execute(web_hook_id: inactive_hook.id,event_type: "post",payload: { test: "some payload" }.to_json,@@ -149,7 +151,7 @@ RSpec.describe Jobs::EmitWebHookEvent dobody: "{\"post\":{\"test\":\"some payload\"}}",).to_return(body: "OK", status: 200)- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: "post",payload: { test: "some payload" }.to_json,@@ -158,7 +160,7 @@ RSpec.describe Jobs::EmitWebHookEvent doit "doesn't emit if the payload URL resolves to a disallowed IP" doFinalDestination::TestHelper.stub_to_fail do- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: "post",payload: { test: "some payload" }.to_json,@@ -179,7 +181,7 @@ RSpec.describe Jobs::EmitWebHookEvent dofab!(:topic_hook) { Fabricate(:topic_web_hook, categories: [category]) }it "doesn't emit when event is not related with defined categories" do- subject.execute(+ job.execute(web_hook_id: topic_hook.id,event_type: "topic",category_id: topic.category.id,@@ -192,7 +194,7 @@ RSpec.describe Jobs::EmitWebHookEvent dobody: "{\"topic\":{\"test\":\"some payload\"}}",).to_return(body: "OK", status: 200)- subject.execute(+ job.execute(web_hook_id: topic_hook.id,event_type: "topic",category_id: topic_with_category.category.id,@@ -207,7 +209,7 @@ RSpec.describe Jobs::EmitWebHookEvent dofab!(:topic_hook) { Fabricate(:topic_web_hook, tags: [tag]) }it "doesn't emit when event is not included any tags" do- subject.execute(+ job.execute(web_hook_id: topic_hook.id,event_type: "topic",payload: { test: "some payload" }.to_json,@@ -215,7 +217,7 @@ RSpec.describe Jobs::EmitWebHookEvent doendit "doesn't emit when event is not related with defined tags" do- subject.execute(+ job.execute(web_hook_id: topic_hook.id,event_type: "topic",tag_ids: [Fabricate(:tag).id],@@ -228,7 +230,7 @@ RSpec.describe Jobs::EmitWebHookEvent dobody: "{\"topic\":{\"test\":\"some payload\"}}",).to_return(body: "OK", status: 200)- subject.execute(+ job.execute(web_hook_id: topic_hook.id,event_type: "topic",tag_ids: topic.tags.pluck(:id),@@ -243,7 +245,7 @@ RSpec.describe Jobs::EmitWebHookEvent dofab!(:like_hook) { Fabricate(:like_web_hook, groups: [group]) }it "doesn't emit when event is not included any groups" do- subject.execute(+ job.execute(web_hook_id: like_hook.id,event_type: "like",payload: { test: "some payload" }.to_json,@@ -251,7 +253,7 @@ RSpec.describe Jobs::EmitWebHookEvent doendit "doesn't emit when event is not related with defined groups" do- subject.execute(+ job.execute(web_hook_id: like_hook.id,event_type: "like",group_ids: [Fabricate(:group).id],@@ -264,7 +266,7 @@ RSpec.describe Jobs::EmitWebHookEvent dobody: "{\"like\":{\"test\":\"some payload\"}}",).to_return(body: "OK", status: 200)- subject.execute(+ job.execute(web_hook_id: like_hook.id,event_type: "like",group_ids: user.groups.pluck(:id),@@ -281,7 +283,7 @@ RSpec.describe Jobs::EmitWebHookEvent doweb_hook_id = Fabricate("#{topic_event_type.name}_web_hook").idexpect do- subject.execute(+ job.execute(web_hook_id: web_hook_id,event_type: topic_event_type.name,payload: { test: "some payload" }.to_json,@@ -298,7 +300,7 @@ RSpec.describe Jobs::EmitWebHookEvent dostatus: 200,)- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: described_class::PING_EVENT,event_name: described_class::PING_EVENT,@@ -324,7 +326,7 @@ RSpec.describe Jobs::EmitWebHookEvent doit "sets up proper request headers when an error raised" dostub_request(:post, post_hook.payload_url).to_raise("error")- subject.execute(+ job.execute(web_hook_id: post_hook.id,event_type: described_class::PING_EVENT,event_name: described_class::PING_EVENT,diff --git a/spec/jobs/enqueue_suspect_users_spec.rb b/spec/jobs/enqueue_suspect_users_spec.rbindex 125e2e0de4c..7ddaada92ea 100644--- a/spec/jobs/enqueue_suspect_users_spec.rb+++ b/spec/jobs/enqueue_suspect_users_spec.rb@@ -1,10 +1,12 @@# frozen_string_literal: trueRSpec.describe Jobs::EnqueueSuspectUsers do+ subject(:job) { described_class.new }+before { SiteSetting.approve_suspect_users = true }it "does nothing when there are no suspect users" do- subject.execute({})+ job.execute({})expect(ReviewableUser.count).to be_zeroend@@ -13,7 +15,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers dolet!(:suspect_user) { Fabricate(:active_user, created_at: 1.day.ago) }it "creates a reviewable when there is a suspect user" do- subject.execute({})+ job.execute({})expect(ReviewableUser.count).to eq(1)end@@ -26,14 +28,14 @@ RSpec.describe Jobs::EnqueueSuspectUsers doreviewable_by_moderator: true,)- subject.execute({})+ job.execute({})expect(ReviewableUser.count).to eq(1)expect(ReviewableUser.last).to eq(review_user)endit "adds a score" do- subject.execute({})+ job.execute({})score = ReviewableScore.lastexpect(score.reason).to eq("suspect_user")@@ -42,7 +44,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers doit "only enqueues non-approved users" dosuspect_user.update!(approved: true)- subject.execute({})+ job.execute({})expect(ReviewableUser.where(target: suspect_user).exists?).to eq(false)end@@ -51,7 +53,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers doSiteSetting.must_approve_users = truesuspect_user.update!(approved: false)- subject.execute({})+ job.execute({})expect(ReviewableUser.where(target: suspect_user).exists?).to eq(false)end@@ -59,7 +61,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers doit "ignores users created more than six months ago" dosuspect_user.update!(created_at: 1.year.ago)- subject.execute({})+ job.execute({})expect(ReviewableUser.where(target: suspect_user).exists?).to eq(false)end@@ -67,7 +69,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers doit "ignores users that were imported from another site" dosuspect_user.upsert_custom_fields({ import_id: "fake_id" })- subject.execute({})+ job.execute({})expect(ReviewableUser.where(target: suspect_user).exists?).to eq(false)end@@ -75,7 +77,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers doit "enqueues a suspect users with custom fields" dosuspect_user.upsert_custom_fields({ field_a: "value", field_b: "value" })- subject.execute({})+ job.execute({})expect(ReviewableUser.where(target: suspect_user).exists?).to eq(true)end@@ -85,7 +87,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers do{ field_a: "value", field_b: "value", import_id: "fake_id" },)- subject.execute({})+ job.execute({})expect(ReviewableUser.where(target: suspect_user).exists?).to eq(false)end@@ -97,7 +99,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers dotime_read: 30.seconds.to_i,)- subject.execute({})+ job.execute({})expect(ReviewableUser.count).to eq(1)end@@ -109,7 +111,7 @@ RSpec.describe Jobs::EnqueueSuspectUsers dotime_read: 2.minutes.to_i,)- subject.execute({})+ job.execute({})expect(ReviewableUser.count).to eq(0)enddiff --git a/spec/jobs/ensure_s3_uploads_existence_spec.rb b/spec/jobs/ensure_s3_uploads_existence_spec.rbindex 84d6e6c812a..846f58b5a5b 100644--- a/spec/jobs/ensure_s3_uploads_existence_spec.rb+++ b/spec/jobs/ensure_s3_uploads_existence_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe Jobs::EnsureS3UploadsExistence do+ subject(:job) { described_class.new }+context "with S3 inventory enabled" dobefore dosetup_s3@@ -9,21 +11,21 @@ RSpec.describe Jobs::EnsureS3UploadsExistence doit "works" doS3Inventory.any_instance.expects(:backfill_etags_and_list_missing).once- subject.execute({})+ job.execute({})endit "doesn't execute when the site was restored within the last 48 hours" doS3Inventory.any_instance.expects(:backfill_etags_and_list_missing).neverBackupMetadata.update_last_restore_date(47.hours.ago)- subject.execute({})+ job.execute({})endit "executes when the site was restored more than 48 hours ago" doS3Inventory.any_instance.expects(:backfill_etags_and_list_missing).onceBackupMetadata.update_last_restore_date(49.hours.ago)- subject.execute({})+ job.execute({})endend@@ -32,7 +34,7 @@ RSpec.describe Jobs::EnsureS3UploadsExistence doit "doesn't execute" doS3Inventory.any_instance.expects(:backfill_etags_and_list_missing).never- subject.execute({})+ job.execute({})endendenddiff --git a/spec/jobs/ignored_users_summary_spec.rb b/spec/jobs/ignored_users_summary_spec.rbindex 461d94081a2..465ed1b3b0f 100644--- a/spec/jobs/ignored_users_summary_spec.rb+++ b/spec/jobs/ignored_users_summary_spec.rb@@ -1,17 +1,17 @@# frozen_string_literal: trueRSpec.describe Jobs::IgnoredUsersSummary do+ subject(:job) { Jobs::IgnoredUsersSummary.new.execute({}) }+before doSiteSetting.ignored_users_count_message_threshold = 1SiteSetting.ignored_users_message_gap_days = 365end- subject { Jobs::IgnoredUsersSummary.new.execute({}) }-context "with no ignored users" doit "does nothing" do- subject- expect { subject }.to_not change { Post.count }+ job+ expect { job }.to_not change { Post.count }endend@@ -30,14 +30,14 @@ RSpec.describe Jobs::IgnoredUsersSummary dobefore { SiteSetting.ignored_users_count_message_threshold = 5 }it "does nothing" do- subject- expect { subject }.to_not change { Post.count }+ job+ expect { job }.to_not change { Post.count }endendcontext "when threshold is hit" doit "creates a system message" do- subject+ jobposts =Post.joins(:topic).where(topics: {@@ -57,15 +57,15 @@ RSpec.describe Jobs::IgnoredUsersSummary dobefore { SiteSetting.ignored_users_count_message_threshold = 5 }it "does nothing" do- subject- expect { subject }.to_not change { Post.count }+ job+ expect { job }.to_not change { Post.count }endendcontext "when threshold is hit" doit "does nothing" do- subject- expect { subject }.to_not change { Post.count }+ job+ expect { job }.to_not change { Post.count }endendenddiff --git a/spec/jobs/invalidate_inactive_admins_spec.rb b/spec/jobs/invalidate_inactive_admins_spec.rbindex 7c070aa5c1d..03707dfed90 100644--- a/spec/jobs/invalidate_inactive_admins_spec.rb+++ b/spec/jobs/invalidate_inactive_admins_spec.rb@@ -1,14 +1,15 @@# frozen_string_literal: trueRSpec.describe Jobs::InvalidateInactiveAdmins do+ subject(:job) { Jobs::InvalidateInactiveAdmins.new.execute({}) }+fab!(:active_admin) { Fabricate(:admin, last_seen_at: 1.hour.ago) }- before { active_admin.email_tokens.update_all(confirmed: true) }- subject { Jobs::InvalidateInactiveAdmins.new.execute({}) }+ before { active_admin.email_tokens.update_all(confirmed: true) }it "does nothing when all admins have been seen recently" doSiteSetting.invalidate_inactive_admin_email_after_days = 365- subject+ jobexpect(active_admin.reload.active).to eq(true)expect(active_admin.email_tokens.where(confirmed: true).exists?).to eq(true)end@@ -21,12 +22,12 @@ RSpec.describe Jobs::InvalidateInactiveAdmins dobefore { SiteSetting.invalidate_inactive_admin_email_after_days = 365 }it "marks email tokens as unconfirmed" do- subject+ jobexpect(not_seen_admin.reload.email_tokens.where(confirmed: true).exists?).to eq(false)endit "makes the user as not active and logs the action" do- subject+ jobexpect(not_seen_admin.reload.active).to eq(false)log = UserHistory.last@@ -35,7 +36,7 @@ RSpec.describe Jobs::InvalidateInactiveAdmins doendit "adds a staff log" do- subject+ jobexpect(not_seen_admin.reload.active).to eq(false)end@@ -52,20 +53,20 @@ RSpec.describe Jobs::InvalidateInactiveAdmins doendit "removes the social logins" do- subject+ jobexpect(UserAssociatedAccount.where(user_id: not_seen_admin.id).exists?).to eq(false)endendit "doesn't deactivate admins with recent posts" doFabricate(:post, user: not_seen_admin)- subject+ jobexpect(not_seen_admin.reload.active).to eq(true)endit "doesn't deactivate admins with recently used api keys" doFabricate(:api_key, user: not_seen_admin, last_used_at: 1.day.ago)- subject+ jobexpect(not_seen_admin.reload.active).to eq(true)endend@@ -74,7 +75,7 @@ RSpec.describe Jobs::InvalidateInactiveAdmins dobefore { SiteSetting.invalidate_inactive_admin_email_after_days = 0 }it "does nothing" do- subject+ jobexpect(active_admin.reload.active).to eq(true)expect(active_admin.email_tokens.where(confirmed: true).exists?).to eq(true)expect(not_seen_admin.reload.active).to eq(true)diff --git a/spec/jobs/post_update_topic_tracking_state_spec.rb b/spec/jobs/post_update_topic_tracking_state_spec.rbindex 442f5574018..144887a9ddb 100644--- a/spec/jobs/post_update_topic_tracking_state_spec.rb+++ b/spec/jobs/post_update_topic_tracking_state_spec.rb@@ -1,16 +1,18 @@# frozen_string_literal: trueRSpec.describe Jobs::PostUpdateTopicTrackingState do+ subject(:job) { described_class.new }+fab!(:post) { Fabricate(:post) }it "should publish messages" do- messages = MessageBus.track_publish { subject.execute({ post_id: post.id }) }+ messages = MessageBus.track_publish { job.execute({ post_id: post.id }) }expect(messages.size).not_to eq(0)endit "should not publish messages for deleted topics" dopost.topic.trash!- messages = MessageBus.track_publish { subject.execute({ post_id: post.id }) }+ messages = MessageBus.track_publish { job.execute({ post_id: post.id }) }expect(messages.size).to eq(0)endenddiff --git a/spec/jobs/process_shelved_notifications_spec.rb b/spec/jobs/process_shelved_notifications_spec.rbindex f0e419f733c..44146c57147 100644--- a/spec/jobs/process_shelved_notifications_spec.rb+++ b/spec/jobs/process_shelved_notifications_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe Jobs::ProcessShelvedNotifications do+ subject(:job) { described_class.new }+fab!(:user) { Fabricate(:user) }let(:post) { Fabricate(:post) }@@ -8,7 +10,7 @@ RSpec.describe Jobs::ProcessShelvedNotifications dofuture = Fabricate(:do_not_disturb_timing, ends_at: 1.day.from_now)past = Fabricate(:do_not_disturb_timing, starts_at: 2.day.ago, ends_at: 1.minute.ago)- expect { subject.execute({}) }.to change { DoNotDisturbTiming.count }.by (-1)+ expect { job.execute({}) }.to change { DoNotDisturbTiming.count }.by (-1)expect(DoNotDisturbTiming.find_by(id: future.id)).to eq(future)expect(DoNotDisturbTiming.find_by(id: past.id)).to eq(nil)end@@ -25,7 +27,7 @@ RSpec.describe Jobs::ProcessShelvedNotifications donotification_type: 1,)expect(notification.shelved_notification).to be_present- subject.execute({})+ job.execute({})expect(notification.shelved_notification).to be_presentend@@ -43,7 +45,7 @@ RSpec.describe Jobs::ProcessShelvedNotifications douser.do_not_disturb_timings.last.update(ends_at: 1.days.ago)expect(notification.shelved_notification).to be_present- subject.execute({})+ job.execute({})expect { notification.shelved_notification.reload }.to raise_error(ActiveRecord::RecordNotFound)endenddiff --git a/spec/jobs/pull_hotlinked_images_spec.rb b/spec/jobs/pull_hotlinked_images_spec.rbindex 3f842c275c1..e722cd35e99 100644--- a/spec/jobs/pull_hotlinked_images_spec.rb+++ b/spec/jobs/pull_hotlinked_images_spec.rb@@ -472,25 +472,25 @@ RSpec.describe Jobs::PullHotlinkedImages doenddescribe "#should_download_image?" do- subject { described_class.new }+ subject(:job) { described_class.new }describe "when url is invalid" doit "should return false" do- expect(subject.should_download_image?("null")).to eq(false)- expect(subject.should_download_image?("meta.discourse.org")).to eq(false)+ expect(job.should_download_image?("null")).to eq(false)+ expect(job.should_download_image?("meta.discourse.org")).to eq(false)endenddescribe "when url is valid" doit "should return true" do- expect(subject.should_download_image?("http://meta.discourse.org")).to eq(true)- expect(subject.should_download_image?("//meta.discourse.org")).to eq(true)+ expect(job.should_download_image?("http://meta.discourse.org")).to eq(true)+ expect(job.should_download_image?("//meta.discourse.org")).to eq(true)endenddescribe "when url is an upload" doit "should return false for original" do- expect(subject.should_download_image?(Fabricate(:upload).url)).to eq(false)+ expect(job.should_download_image?(Fabricate(:upload).url)).to eq(false)endcontext "when secure uploads enabled" do@@ -501,19 +501,19 @@ RSpec.describe Jobs::PullHotlinkedImages doupload = Fabricate(:upload_s3, secure: true)stub_s3(upload)url = Upload.secure_uploads_url_from_upload_url(upload.url)- expect(subject.should_download_image?(url)).to eq(false)+ expect(job.should_download_image?(url)).to eq(false)endendit "should return true for optimized" dosrc = Discourse.store.get_path_for_optimized_image(Fabricate(:optimized_image))- expect(subject.should_download_image?(src)).to eq(true)+ expect(job.should_download_image?(src)).to eq(true)endendit "returns false for emoji" dosrc = Emoji.url_for("testemoji.png")- expect(subject.should_download_image?(src)).to eq(false)+ expect(job.should_download_image?(src)).to eq(false)endit "returns false for emoji when app and S3 CDNs configured" do@@ -522,14 +522,14 @@ RSpec.describe Jobs::PullHotlinkedImages doset_cdn_url "https://mydomain.cdn/test"src = UrlHelper.cook_url(Emoji.url_for("testemoji.png"))- expect(subject.should_download_image?(src)).to eq(false)+ expect(job.should_download_image?(src)).to eq(false)endit "returns false for emoji when emoji CDN configured" doSiteSetting.external_emoji_url = "https://emoji.cdn.com"src = UrlHelper.cook_url(Emoji.url_for("testemoji.png"))- expect(subject.should_download_image?(src)).to eq(false)+ expect(job.should_download_image?(src)).to eq(false)endit "returns false for emoji when app, S3 *and* emoji CDNs configured" do@@ -539,17 +539,17 @@ RSpec.describe Jobs::PullHotlinkedImages doset_cdn_url "https://mydomain.cdn/test"src = UrlHelper.cook_url(Emoji.url_for("testemoji.png"))- expect(subject.should_download_image?(src)).to eq(false)+ expect(job.should_download_image?(src)).to eq(false)endit "returns false for plugin assets" dosrc = UrlHelper.cook_url("/plugins/discourse-amazing-plugin/myasset.png")- expect(subject.should_download_image?(src)).to eq(false)+ expect(job.should_download_image?(src)).to eq(false)endit "returns false for local non-uploaded files" dosrc = UrlHelper.cook_url("/mycustomroute.png")- expect(subject.should_download_image?(src)).to eq(false)+ expect(job.should_download_image?(src)).to eq(false)endcontext "when download_remote_images_to_local? is false" do@@ -557,11 +557,11 @@ RSpec.describe Jobs::PullHotlinkedImages doit "still returns true for optimized" dosrc = Discourse.store.get_path_for_optimized_image(Fabricate(:optimized_image))- expect(subject.should_download_image?(src)).to eq(true)+ expect(job.should_download_image?(src)).to eq(true)endit "returns false for valid remote URLs" do- expect(subject.should_download_image?("http://meta.discourse.org")).to eq(false)+ expect(job.should_download_image?("http://meta.discourse.org")).to eq(false)endendenddiff --git a/spec/jobs/purge_expired_ignored_users_spec.rb b/spec/jobs/purge_expired_ignored_users_spec.rbindex 67f74e53310..90e4c6e86c4 100644--- a/spec/jobs/purge_expired_ignored_users_spec.rb+++ b/spec/jobs/purge_expired_ignored_users_spec.rb@@ -1,11 +1,11 @@# frozen_string_literal: trueRSpec.describe Jobs::PurgeExpiredIgnoredUsers do- subject { Jobs::PurgeExpiredIgnoredUsers.new.execute({}) }+ subject(:job) { Jobs::PurgeExpiredIgnoredUsers.new.execute({}) }context "with no ignored users" doit "does nothing" do- expect { subject }.to_not change { IgnoredUser.count }+ expect { job }.to_not change { IgnoredUser.count }endend@@ -21,7 +21,7 @@ RSpec.describe Jobs::PurgeExpiredIgnoredUsers docontext "when no expired ignored users" doit "does nothing" do- expect { subject }.to_not change { IgnoredUser.count }+ expect { job }.to_not change { IgnoredUser.count }endend@@ -32,7 +32,7 @@ RSpec.describe Jobs::PurgeExpiredIgnoredUsers doFabricate(:ignored_user, user: tarek, ignored_user: fred, expiring_at: 1.month.from_now)freeze_time(2.months.from_now) do- subject+ jobexpect(IgnoredUser.find_by(ignored_user: fred)).to be_nilendenddiff --git a/spec/jobs/regular/group_smtp_email_spec.rb b/spec/jobs/regular/group_smtp_email_spec.rbindex 475e939d9b1..25108a6d2a1 100644--- a/spec/jobs/regular/group_smtp_email_spec.rb+++ b/spec/jobs/regular/group_smtp_email_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe Jobs::GroupSmtpEmail do+ subject(:job) { described_class.new }+fab!(:topic) { Fabricate(:private_message_topic, title: "Help I need support") }fab!(:post) doFabricate(:post, topic: topic, raw: "some first post content")@@ -46,11 +48,11 @@ RSpec.describe Jobs::GroupSmtpEmail dobcc_addresses: [],).returns(message)- subject.execute(args)+ job.execute(args)endit "includes a 'reply above this line' message" do- subject.execute(args)+ job.execute(args)email_log =EmailLog.find_by(post_id: post.id, topic_id: post.topic_id, user_id: recipient_user.id)expect(email_log.as_mail_message.html_part.to_s).to include(@@ -59,7 +61,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "does not include context posts" do- subject.execute(args)+ job.execute(args)email_log =EmailLog.find_by(post_id: post.id, topic_id: post.topic_id, user_id: recipient_user.id)expect(email_log.as_mail_message.text_part.to_s).not_to include(@@ -72,7 +74,7 @@ RSpec.describe Jobs::GroupSmtpEmail dosecond_post = topic.posts.find_by(post_number: 2)post.update!(reply_to_post_number: 1, reply_to_user: second_post.user)PostReply.create(post: second_post, reply: post)- subject.execute(args)+ job.execute(args)email_log =EmailLog.find_by(post_id: post.id, topic_id: post.topic_id, user_id: recipient_user.id)expect(email_log.raw_headers).to include(@@ -84,7 +86,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "includes the participants in the correct format (but not the recipient user), and does not have links for the staged users" do- subject.execute(args)+ job.execute(args)email_log =EmailLog.find_by(post_id: post.id, topic_id: post.topic_id, user_id: recipient_user.id)email_text = email_log.as_mail_message.text_part.to_s@@ -98,7 +100,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "creates an EmailLog record with the correct details" do- subject.execute(args)+ job.execute(args)email_log =EmailLog.find_by(post_id: post.id, topic_id: post.topic_id, user_id: recipient_user.id)expect(email_log).not_to eq(nil)@@ -106,7 +108,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "creates an IncomingEmail record with the correct details to avoid double processing IMAP" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")incoming_email =@@ -120,7 +122,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "does not create a post reply key, it always replies to the group email_username" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")email_log =@@ -132,7 +134,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "creates an EmailLog record with the correct details" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")email_log =@@ -142,7 +144,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "creates an IncomingEmail record with the correct details to avoid double processing IMAP" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")incoming_email =@@ -156,7 +158,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "does not create a post reply key, it always replies to the group email_username" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")email_log =@@ -169,7 +171,7 @@ RSpec.describe Jobs::GroupSmtpEmail doit "falls back to the group name if full name is blank" dogroup.update(full_name: "")- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")email_log =@@ -178,7 +180,7 @@ RSpec.describe Jobs::GroupSmtpEmail doendit "has the group_smtp_id and the to_address filled in correctly" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)expect(ActionMailer::Base.deliveries.last.subject).to eq("Re: Help I need support")email_log =@@ -190,7 +192,7 @@ RSpec.describe Jobs::GroupSmtpEmail doit "drops malformed cc addresses when sending the email" doargs2 = args.cloneargs2[:cc_emails] << "[email protected]<mailto:[email protected]"- subject.execute(args2)+ job.execute(args2)expect(ActionMailer::Base.deliveries.count).to eq(1)last_email = ActionMailer::Base.deliveries.lastexpect(last_email.subject).to eq("Re: Help I need support")@@ -199,7 +201,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when there are cc_addresses" doit "has the cc_addresses and cc_user_ids filled in correctly" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)sent_mail = ActionMailer::Base.deliveries.lastexpect(sent_mail.subject).to eq("Re: Help I need support")@@ -212,7 +214,7 @@ RSpec.describe Jobs::GroupSmtpEmail doit "where cc_addresses match non-staged users, convert to bcc_addresses" dostaged2.update!(staged: false, active: true)- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)sent_mail = ActionMailer::Base.deliveries.lastexpect(sent_mail.subject).to eq("Re: Help I need support")@@ -233,7 +235,7 @@ RSpec.describe Jobs::GroupSmtpEmail dobefore { group.update!(imap_enabled: true) }it "aborts and does not send a group SMTP email; the OP is the one that sent the email in the first place" do- expect { subject.execute(args) }.not_to(change { EmailLog.count })+ expect { job.execute(args) }.not_to(change { EmailLog.count })expect(ActionMailer::Base.deliveries.count).to eq(0)endend@@ -242,7 +244,7 @@ RSpec.describe Jobs::GroupSmtpEmail dobefore { group.update!(imap_enabled: false) }it "sends the email as expected" do- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(1)endend@@ -251,7 +253,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when the post is deleted" doit "aborts and adds a skipped email log" dopost.trash!- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(0)expect(SkippedEmailLog.exists?(@@ -268,7 +270,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when the topic is deleted" doit "aborts and adds a skipped email log" dopost.topic.trash!- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(0)expect(SkippedEmailLog.exists?(@@ -285,7 +287,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when smtp is not enabled" doit "returns without sending email" doSiteSetting.enable_smtp = false- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(0)endend@@ -293,7 +295,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when disable_emails is yes" doit "returns without sending email" doSiteSetting.disable_emails = "yes"- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(0)endend@@ -301,7 +303,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when group is deleted" doit "returns without sending email" dogroup.destroy- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(0)endend@@ -309,7 +311,7 @@ RSpec.describe Jobs::GroupSmtpEmail docontext "when smtp is not enabled for the group" doit "returns without sending email" dogroup.update!(smtp_enabled: false)- subject.execute(args)+ job.execute(args)expect(ActionMailer::Base.deliveries.count).to eq(0)expect(SkippedEmailLog.exists?(diff --git a/spec/jobs/regular/publish_group_membership_updates_spec.rb b/spec/jobs/regular/publish_group_membership_updates_spec.rbindex 6f5479b090b..559df03ecdd 100644--- a/spec/jobs/regular/publish_group_membership_updates_spec.rb+++ b/spec/jobs/regular/publish_group_membership_updates_spec.rb@@ -1,13 +1,15 @@# frozen_string_literal: truedescribe Jobs::PublishGroupMembershipUpdates do+ subject(:job) { described_class.new }+fab!(:user) { Fabricate(:user) }fab!(:group) { Fabricate(:group) }it "publishes events for added users" doevents =DiscourseEvent.track_events do- subject.execute(user_ids: [user.id], group_id: group.id, type: "add")+ job.execute(user_ids: [user.id], group_id: group.id, type: "add")endexpect(events).to include(@@ -19,7 +21,7 @@ describe Jobs::PublishGroupMembershipUpdates doit "publishes events for removed users" doevents =DiscourseEvent.track_events do- subject.execute(user_ids: [user.id], group_id: group.id, type: "remove")+ job.execute(user_ids: [user.id], group_id: group.id, type: "remove")endexpect(events).to include(event_name: :user_removed_from_group, params: [user, group])@@ -27,9 +29,7 @@ describe Jobs::PublishGroupMembershipUpdates doit "does nothing if the group doesn't exist" doevents =- DiscourseEvent.track_events do- subject.execute(user_ids: [user.id], group_id: nil, type: "add")- end+ DiscourseEvent.track_events { job.execute(user_ids: [user.id], group_id: nil, type: "add") }expect(events).not_to include(event_name: :user_added_to_group,@@ -38,7 +38,7 @@ describe Jobs::PublishGroupMembershipUpdates doendit "fails when the update type is invalid" do- expect { subject.execute(user_ids: [user.id], group_id: nil, type: nil) }.to raise_error(+ expect { job.execute(user_ids: [user.id], group_id: nil, type: nil) }.to raise_error(Discourse::InvalidParameters,)end@@ -46,7 +46,7 @@ describe Jobs::PublishGroupMembershipUpdates doit "does nothing when the user is not human" doevents =DiscourseEvent.track_events do- subject.execute(user_ids: [Discourse.system_user.id], group_id: nil, type: "add")+ job.execute(user_ids: [Discourse.system_user.id], group_id: nil, type: "add")endexpect(events).not_to include(diff --git a/spec/jobs/reindex_search_spec.rb b/spec/jobs/reindex_search_spec.rbindex a9885598d2c..0aefc88afbb 100644--- a/spec/jobs/reindex_search_spec.rb+++ b/spec/jobs/reindex_search_spec.rb@@ -1,12 +1,15 @@# frozen_string_literal: trueRSpec.describe Jobs::ReindexSearch do+ subject(:job) { described_class.new }++ let(:locale) { "fr" }+before doSearchIndexer.enableJobs.run_immediately!end- let(:locale) { "fr" }# This works since test db has a small record less than limit.# Didn't check `topic` because topic doesn't have posts in fabrication# thus no search data@@ -15,7 +18,7 @@ RSpec.describe Jobs::ReindexSearch doSiteSetting.default_locale = "en"model = Fabricate(m.to_sym)SiteSetting.default_locale = locale- subject.execute({})+ job.execute({})expect(model.public_send("#{m}_search_data").locale).to eq localeend@@ -26,7 +29,7 @@ RSpec.describe Jobs::ReindexSearch dosearch_data.update!(version: 0)model.reload- subject.execute({})+ job.execute({})expect(model.public_send("#{m}_search_data").version).to eq("SearchIndexer::#{m.upcase}_INDEX_VERSION".constantize,)@@ -64,7 +67,7 @@ RSpec.describe Jobs::ReindexSearch dopost2.topic.trash!post3.trash!- subject.rebuild_posts(indexer: FakeIndexer)+ job.rebuild_posts(indexer: FakeIndexer)expect(FakeIndexer.posts).to contain_exactly(post)end@@ -72,7 +75,7 @@ RSpec.describe Jobs::ReindexSearch doit "should not reindex posts with a developmental version" doFabricate(:post, version: SearchIndexer::POST_INDEX_VERSION + 1)- subject.rebuild_posts(indexer: FakeIndexer)+ job.rebuild_posts(indexer: FakeIndexer)expect(FakeIndexer.posts).to eq([])end@@ -85,7 +88,7 @@ RSpec.describe Jobs::ReindexSearch dopost2.save!(validate: false)- subject.rebuild_posts(indexer: FakeIndexer)+ job.rebuild_posts(indexer: FakeIndexer)expect(FakeIndexer.posts).to contain_exactly(post)end@@ -100,7 +103,7 @@ RSpec.describe Jobs::ReindexSearch dofreeze_time(1.day.ago) { topic.trash! }- expect { subject.execute({}) }.to change { TopicSearchData.count }.by(-1)+ expect { job.execute({}) }.to change { TopicSearchData.count }.by(-1)expect(Topic.pluck(:id)).to contain_exactly(topic2.id)expect(TopicSearchData.pluck(:topic_id)).to contain_exactly(topic2.topic_search_data.topic_id)@@ -124,7 +127,7 @@ RSpec.describe Jobs::ReindexSearch dopost6.trash!end- expect { subject.execute({}) }.to change { PostSearchData.count }.by(-3)+ expect { job.execute({}) }.to change { PostSearchData.count }.by(-3)expect(Post.pluck(:id)).to contain_exactly(post.id, post2.id, post3.id, post4.id, post5.id)diff --git a/spec/jobs/sync_topic_user_bookmarked_spec.rb b/spec/jobs/sync_topic_user_bookmarked_spec.rbindex 3938085fe38..a66ea21393c 100644--- a/spec/jobs/sync_topic_user_bookmarked_spec.rb+++ b/spec/jobs/sync_topic_user_bookmarked_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe Jobs::SyncTopicUserBookmarked do+ subject(:job) { described_class.new }+fab!(:topic) { Fabricate(:topic) }fab!(:post1) { Fabricate(:post, topic: topic) }fab!(:post2) { Fabricate(:post, topic: topic) }@@ -16,7 +18,7 @@ RSpec.describe Jobs::SyncTopicUserBookmarked doFabricate(:bookmark, user: tu1.user, bookmarkable: topic.posts.sample)Fabricate(:bookmark, user: tu4.user, bookmarkable: topic.posts.sample)- subject.execute(topic_id: topic.id)+ job.execute(topic_id: topic.id)expect(tu1.reload.bookmarked).to eq(true)expect(tu2.reload.bookmarked).to eq(false)@@ -31,7 +33,7 @@ RSpec.describe Jobs::SyncTopicUserBookmarked dopost1.trash!- subject.execute(topic_id: topic.id)+ job.execute(topic_id: topic.id)expect(tu1.reload.bookmarked).to eq(false)expect(tu2.reload.bookmarked).to eq(false)@@ -41,7 +43,7 @@ RSpec.describe Jobs::SyncTopicUserBookmarked doFabricate(:bookmark, user: tu1.user, bookmarkable: topic.posts.sample)Fabricate(:bookmark, user: tu4.user, bookmarkable: topic.posts.sample)- subject.execute+ job.executeexpect(tu1.reload.bookmarked).to eq(true)expect(tu2.reload.bookmarked).to eq(false)diff --git a/spec/jobs/topic_timer_enqueuer_spec.rb b/spec/jobs/topic_timer_enqueuer_spec.rbindex 95f73fd93ef..1d8fa534b3c 100644--- a/spec/jobs/topic_timer_enqueuer_spec.rb+++ b/spec/jobs/topic_timer_enqueuer_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe Jobs::TopicTimerEnqueuer do- subject { described_class.new }+ subject(:job) { described_class.new }fab!(:timer1) doFabricate(@@ -40,20 +40,20 @@ RSpec.describe Jobs::TopicTimerEnqueuer doit "does not enqueue deleted timers" doexpect_not_enqueued_with(job: :close_topic, args: { topic_timer_id: deleted_timer.id })- subject.execute+ job.executeexpect(deleted_timer.topic.reload.closed?).to eq(false)endit "does not enqueue future timers" doexpect_not_enqueued_with(job: :close_topic, args: { topic_timer_id: future_timer.id })- subject.execute+ job.executeexpect(future_timer.topic.reload.closed?).to eq(false)endit "enqueues the related job" doexpect_not_enqueued_with(job: :close_topic, args: { topic_timer_id: deleted_timer.id })expect_not_enqueued_with(job: :close_topic, args: { topic_timer_id: future_timer.id })- subject.execute+ job.executeexpect_job_enqueued(job: :close_topic, args: { topic_timer_id: timer1.id })expect_job_enqueued(job: :open_topic, args: { topic_timer_id: timer2.id })end@@ -61,11 +61,11 @@ RSpec.describe Jobs::TopicTimerEnqueuer doit "does not re-enqueue a job that has already been scheduled ahead of time in sidekiq (legacy topic timers)" doexpect_not_enqueued_with(job: :close_topic, args: { topic_timer_id: timer1.id })Jobs.enqueue_at(1.hours.from_now, :close_topic, topic_timer_id: timer1.id)- subject.execute+ job.executeendit "does not fail to enqueue other timers just because one timer errors" doTopicTimer.any_instance.stubs(:enqueue_typed_job).raises(StandardError).then.returns(true)- expect { subject.execute }.not_to raise_error+ expect { job.execute }.not_to raise_errorendenddiff --git a/spec/lib/backup_restore/database_restorer_multisite_spec.rb b/spec/lib/backup_restore/database_restorer_multisite_spec.rbindex 19044c1f726..0da53b7513b 100644--- a/spec/lib/backup_restore/database_restorer_multisite_spec.rb+++ b/spec/lib/backup_restore/database_restorer_multisite_spec.rb@@ -3,12 +3,12 @@require_relative "shared_context_for_backup_restore"RSpec.describe BackupRestore::DatabaseRestorer, type: :multisite do+ subject(:restorer) { BackupRestore::DatabaseRestorer.new(logger, current_db) }+include_context "with shared stuff"let(:current_db) { RailsMultisite::ConnectionManagement.current_db }- subject { BackupRestore::DatabaseRestorer.new(logger, current_db) }-describe "#restore" docontext "with database connection" doit "reconnects to the correct database" dodiff --git a/spec/lib/backup_restore/database_restorer_spec.rb b/spec/lib/backup_restore/database_restorer_spec.rbindex afa4bea4f36..8d8711e9247 100644--- a/spec/lib/backup_restore/database_restorer_spec.rb+++ b/spec/lib/backup_restore/database_restorer_spec.rb@@ -3,12 +3,12 @@require_relative "shared_context_for_backup_restore"RSpec.describe BackupRestore::DatabaseRestorer do+ subject(:restorer) { BackupRestore::DatabaseRestorer.new(logger, current_db) }+include_context "with shared stuff"let(:current_db) { RailsMultisite::ConnectionManagement.current_db }- subject { BackupRestore::DatabaseRestorer.new(logger, current_db) }-describe "#restore" doit "executes everything in the correct order" dorestore = sequence("restore")@@ -18,7 +18,7 @@ RSpec.describe BackupRestore::DatabaseRestorer doexpect_db_migrate.in_sequence(restore)expect_db_reconnect.in_sequence(restore)- subject.restore("foo.sql")+ restorer.restore("foo.sql")endit "stores the date of the last restore" do@@ -146,12 +146,12 @@ RSpec.describe BackupRestore::DatabaseRestorer doit "moves tables back when tables were moved" doBackupRestore.stubs(:can_rollback?).returns(true)BackupRestore.expects(:move_tables_between_schemas).with("backup", "public").never- subject.rollback+ restorer.rollbackexecute_stubbed_restoreBackupRestore.expects(:move_tables_between_schemas).with("backup", "public").once- subject.rollback+ restorer.rollbackendend@@ -164,7 +164,7 @@ RSpec.describe BackupRestore::DatabaseRestorer doit "doesn't try to drop function when no functions have been created" doMigration::BaseDropper.expects(:drop_readonly_function).never- subject.clean_up+ restorer.clean_upendit "creates and drops all functions when none exist" do@@ -174,7 +174,7 @@ RSpec.describe BackupRestore::DatabaseRestorer doMigration::BaseDropper.expects(:drop_readonly_function).with(:posts, :via_email)Migration::BaseDropper.expects(:drop_readonly_function).with(:posts, :raw_email)- subject.clean_up+ restorer.clean_upendit "creates and drops only missing functions during restore" do@@ -186,19 +186,17 @@ RSpec.describe BackupRestore::DatabaseRestorer doexecute_stubbed_restore(stub_readonly_functions: false)Migration::BaseDropper.expects(:drop_readonly_function).with(:posts, :via_email)- subject.clean_up+ restorer.clean_upendenddescribe ".drop_backup_schema" do- subject { BackupRestore::DatabaseRestorer }-context "when no backup schema exists" doit "doesn't do anything" doActiveRecord::Base.connection.expects(:schema_exists?).with("backup").returns(false)ActiveRecord::Base.connection.expects(:drop_schema).never- subject.drop_backup_schema+ described_class.drop_backup_schemaendend@@ -209,14 +207,14 @@ RSpec.describe BackupRestore::DatabaseRestorer doActiveRecord::Base.connection.expects(:drop_schema).with("backup")BackupMetadata.update_last_restore_date(8.days.ago)- subject.drop_backup_schema+ described_class.drop_backup_schemaendit "doesn't drop the schema when the last restore was recently" doActiveRecord::Base.connection.expects(:drop_schema).with("backup").neverBackupMetadata.update_last_restore_date(6.days.ago)- subject.drop_backup_schema+ described_class.drop_backup_schemaendit "stores the current date when there is no record of the last restore" do@@ -225,7 +223,7 @@ RSpec.describe BackupRestore::DatabaseRestorer dodate_string = "2020-01-08T17:38:27Z"freeze_time(Time.parse(date_string))- subject.drop_backup_schema+ described_class.drop_backup_schemaexpect(BackupMetadata.value_for(BackupMetadata::LAST_RESTORE_DATE)).to eq(date_string)endenddiff --git a/spec/lib/backup_restore/local_backup_store_spec.rb b/spec/lib/backup_restore/local_backup_store_spec.rbindex 345fb4e4d16..4eb51f257ce 100644--- a/spec/lib/backup_restore/local_backup_store_spec.rb+++ b/spec/lib/backup_restore/local_backup_store_spec.rb@@ -4,6 +4,8 @@ require "backup_restore/local_backup_store"require_relative "shared_examples_for_backup_store"RSpec.describe BackupRestore::LocalBackupStore do+ subject(:store) { BackupRestore::BackupStore.create(root_directory: @root_directory) }+before do@root_directory = Dir.mktmpdir@paths = []@@ -12,7 +14,6 @@ RSpec.describe BackupRestore::LocalBackupStore doafter { FileUtils.remove_dir(@root_directory, true) }- subject(:store) { BackupRestore::BackupStore.create(root_directory: @root_directory) }let(:expected_type) { BackupRestore::LocalBackupStore }it_behaves_like "backup store"diff --git a/spec/lib/backup_restore/s3_backup_store_spec.rb b/spec/lib/backup_restore/s3_backup_store_spec.rbindex 7989fbaa4d8..297572e131f 100644--- a/spec/lib/backup_restore/s3_backup_store_spec.rb+++ b/spec/lib/backup_restore/s3_backup_store_spec.rb@@ -5,6 +5,8 @@ require "backup_restore/s3_backup_store"require_relative "shared_examples_for_backup_store"RSpec.describe BackupRestore::S3BackupStore do+ subject(:store) { BackupRestore::BackupStore.create(s3_options: @s3_options) }+before do@s3_client = Aws::S3::Client.new(stub_responses: true)@s3_options = { client: @s3_client }@@ -86,7 +88,6 @@ RSpec.describe BackupRestore::S3BackupStore doSiteSetting.backup_location = BackupLocationSiteSetting::S3end- subject(:store) { BackupRestore::BackupStore.create(s3_options: @s3_options) }let(:expected_type) { BackupRestore::S3BackupStore }it_behaves_like "backup store"diff --git a/spec/lib/backup_restore/system_interface_multisite_spec.rb b/spec/lib/backup_restore/system_interface_multisite_spec.rbindex dbc669ca7e8..5b656933a40 100644--- a/spec/lib/backup_restore/system_interface_multisite_spec.rb+++ b/spec/lib/backup_restore/system_interface_multisite_spec.rb@@ -3,9 +3,9 @@require_relative "shared_context_for_backup_restore"RSpec.describe BackupRestore::SystemInterface, type: :multisite do- include_context "with shared stuff"+ subject(:system_interface) { BackupRestore::SystemInterface.new(logger) }- subject { BackupRestore::SystemInterface.new(logger) }+ include_context "with shared stuff"describe "#flush_redis" doit "removes only keys from the current site in a multisite" do@@ -24,7 +24,7 @@ RSpec.describe BackupRestore::SystemInterface, type: :multisite doexpect(Discourse.redis.get("foo")).to eq("second-foo")expect(Discourse.redis.get("bar")).to eq("second-bar")- subject.flush_redis+ system_interface.flush_redisexpect(Discourse.redis.get("foo")).to be_nilexpect(Discourse.redis.get("bar")).to be_nil@@ -43,7 +43,7 @@ RSpec.describe BackupRestore::SystemInterface, type: :multisite doBackupRestore.mark_as_running!expect do- thread = subject.listen_for_shutdown_signal+ thread = system_interface.listen_for_shutdown_signalBackupRestore.set_shutdown_signal!thread.joinend.to raise_error(SystemExit)diff --git a/spec/lib/backup_restore/system_interface_spec.rb b/spec/lib/backup_restore/system_interface_spec.rbindex 8f1461cc17c..e22b90daa6f 100644--- a/spec/lib/backup_restore/system_interface_spec.rb+++ b/spec/lib/backup_restore/system_interface_spec.rb@@ -3,9 +3,9 @@require_relative "shared_context_for_backup_restore"RSpec.describe BackupRestore::SystemInterface do- include_context "with shared stuff"+ subject(:system_interface) { BackupRestore::SystemInterface.new(logger) }- subject { BackupRestore::SystemInterface.new(logger) }+ include_context "with shared stuff"describe "readonly mode" doafter { Discourse::READONLY_KEYS.each { |key| Discourse.redis.del(key) } }@@ -13,26 +13,26 @@ RSpec.describe BackupRestore::SystemInterface dodescribe "#enable_readonly_mode" doit "enables readonly mode" doDiscourse.expects(:enable_readonly_mode).once- subject.enable_readonly_mode+ system_interface.enable_readonly_modeendit "does not enable readonly mode when it is already in readonly mode" doDiscourse.enable_readonly_modeDiscourse.expects(:enable_readonly_mode).never- subject.enable_readonly_mode+ system_interface.enable_readonly_modeendenddescribe "#disable_readonly_mode" doit "disables readonly mode" doDiscourse.expects(:disable_readonly_mode).once- subject.disable_readonly_mode+ system_interface.disable_readonly_modeendit "does not disable readonly mode when readonly mode was explicitly enabled" doDiscourse.enable_readonly_modeDiscourse.expects(:disable_readonly_mode).never- subject.disable_readonly_mode+ system_interface.disable_readonly_modeendendend@@ -40,14 +40,14 @@ RSpec.describe BackupRestore::SystemInterface dodescribe "#mark_restore_as_running" doit "calls mark_restore_as_running" doBackupRestore.expects(:mark_as_running!).once- subject.mark_restore_as_running+ system_interface.mark_restore_as_runningendenddescribe "#mark_restore_as_not_running" doit "calls mark_restore_as_not_running" doBackupRestore.expects(:mark_as_not_running!).once- subject.mark_restore_as_not_running+ system_interface.mark_restore_as_not_runningendend@@ -61,7 +61,7 @@ RSpec.describe BackupRestore::SystemInterface doit "exits the process when shutdown signal is set" doexpect do- thread = subject.listen_for_shutdown_signal+ thread = system_interface.listen_for_shutdown_signalBackupRestore.set_shutdown_signal!thread.joinend.to raise_error(SystemExit)@@ -71,7 +71,7 @@ RSpec.describe BackupRestore::SystemInterface doBackupRestore.set_shutdown_signal!expect(BackupRestore.should_shutdown?).to eq(true)- thread = subject.listen_for_shutdown_signal+ thread = system_interface.listen_for_shutdown_signalexpect(BackupRestore.should_shutdown?).to eq(false)Thread.kill(thread)end@@ -82,7 +82,7 @@ RSpec.describe BackupRestore::SystemInterface doit "calls pause!" doexpect(Sidekiq.paused?).to eq(false)- subject.pause_sidekiq("my reason")+ system_interface.pause_sidekiq("my reason")expect(Sidekiq.paused?).to eq(true)expect(Discourse.redis.get(SidekiqPauser::PAUSED_KEY)).to eq("my reason")end@@ -93,15 +93,15 @@ RSpec.describe BackupRestore::SystemInterface doSidekiq.pause!expect(Sidekiq.paused?).to eq(true)- subject.unpause_sidekiq+ system_interface.unpause_sidekiqexpect(Sidekiq.paused?).to eq(false)endenddescribe "#wait_for_sidekiq" doit "waits 6 seconds even when there are no running Sidekiq jobs" do- subject.expects(:sleep).with(6).once- subject.wait_for_sidekiq+ system_interface.expects(:sleep).with(6).once+ system_interface.wait_for_sidekiqendcontext "with Sidekiq workers" do@@ -146,22 +146,26 @@ RSpec.describe BackupRestore::SystemInterface doendit "waits up to 60 seconds for jobs running for the current site to finish" do- subject.expects(:sleep).with(6).times(10)+ system_interface.expects(:sleep).with(6).times(10)create_workers- expect { subject.wait_for_sidekiq }.to raise_error(BackupRestore::RunningSidekiqJobsError)+ expect { system_interface.wait_for_sidekiq }.to raise_error(+ BackupRestore::RunningSidekiqJobsError,+ )endit "waits up to 60 seconds for jobs running on all sites to finish" do- subject.expects(:sleep).with(6).times(10)+ system_interface.expects(:sleep).with(6).times(10)create_workers(all_sites: true)- expect { subject.wait_for_sidekiq }.to raise_error(BackupRestore::RunningSidekiqJobsError)+ expect { system_interface.wait_for_sidekiq }.to raise_error(+ BackupRestore::RunningSidekiqJobsError,+ )endit "ignores jobs of other sites" do- subject.expects(:sleep).with(6).once+ system_interface.expects(:sleep).with(6).oncecreate_workers(site_id: "another_site")- subject.wait_for_sidekiq+ system_interface.wait_for_sidekiqendendend@@ -172,7 +176,7 @@ RSpec.describe BackupRestore::SystemInterface doit "doesn't unpause Sidekiq" doSidekiq.pause!- subject.flush_redis+ system_interface.flush_redisexpect(Sidekiq.paused?).to eq(true)enddiff --git a/spec/lib/backup_restore/uploads_restorer_spec.rb b/spec/lib/backup_restore/uploads_restorer_spec.rbindex ff00811c9aa..079b5513aba 100644--- a/spec/lib/backup_restore/uploads_restorer_spec.rb+++ b/spec/lib/backup_restore/uploads_restorer_spec.rb@@ -4,9 +4,9 @@require_relative "shared_context_for_backup_restore"RSpec.describe BackupRestore::UploadsRestorer do- include_context "with shared stuff"+ subject(:restorer) { BackupRestore::UploadsRestorer.new(logger) }- subject { BackupRestore::UploadsRestorer.new(logger) }+ include_context "with shared stuff"def with_temp_uploads_directory(name: "default", with_optimized: false)Dir.mktmpdir do |directory|@@ -93,7 +93,7 @@ RSpec.describe BackupRestore::UploadsRestorer dodef setup_and_restore(directory, metadata)metadata.each { |d| BackupMetadata.create!(d) }- subject.restore(directory)+ restorer.restore(directory)enddef uploads_path(database)@@ -119,15 +119,15 @@ RSpec.describe BackupRestore::UploadsRestorer dolet(:target_site_name) { target_site_type == multisite ? "second" : "default" }let(:target_hostname) { target_site_type == multisite ? "test2.localhost" : "test.localhost" }- shared_context "with no uploads" do+ shared_examples "with no uploads" doit "does nothing when temporary uploads directory is missing or empty" dostore_class.any_instance.expects(:copy_from).neverDir.mktmpdir do |directory|- subject.restore(directory)+ restorer.restore(directory)FileUtils.mkdir(File.join(directory, "uploads"))- subject.restore(directory)+ restorer.restore(directory)endendend@@ -176,7 +176,7 @@ RSpec.describe BackupRestore::UploadsRestorer dowith_temp_uploads_directory do |directory, path|store_class.any_instance.expects(:copy_from).with(path).once- expect { subject.restore(directory) }.to change { OptimizedImage.count }.by_at_most(+ expect { restorer.restore(directory) }.to change { OptimizedImage.count }.by_at_most(-1,).and change { Jobs::CreateAvatarThumbnails.jobs.size }.by(1).and change {Post.where(baked_version: nil).count@@ -190,7 +190,7 @@ RSpec.describe BackupRestore::UploadsRestorer dowith_temp_uploads_directory(with_optimized: true) do |directory, path|store_class.any_instance.expects(:copy_from).with(path).once- expect { subject.restore(directory) }.to not_change {+ expect { restorer.restore(directory) }.to not_change {OptimizedImage.count}.and not_change { Jobs::CreateAvatarThumbnails.jobs.size }.and change {Post.where(baked_version: nil).count@@ -609,14 +609,14 @@ RSpec.describe BackupRestore::UploadsRestorer doDiscourse.stubs(:store).returns(Object.new)with_temp_uploads_directory do |directory|- expect { subject.restore(directory) }.to raise_error(BackupRestore::UploadsRestoreError)+ expect { restorer.restore(directory) }.to raise_error(BackupRestore::UploadsRestoreError)endendit "raises an exception when there are multiple folders in the uploads directory" dowith_temp_uploads_directory do |directory|FileUtils.mkdir_p(File.join(directory, "uploads", "foo"))- expect { subject.restore(directory) }.to raise_error(BackupRestore::UploadsRestoreError)+ expect { restorer.restore(directory) }.to raise_error(BackupRestore::UploadsRestoreError)endenddiff --git a/spec/lib/bookmark_manager_spec.rb b/spec/lib/bookmark_manager_spec.rbindex 164cee18727..24ab55a7d80 100644--- a/spec/lib/bookmark_manager_spec.rb+++ b/spec/lib/bookmark_manager_spec.rb@@ -1,25 +1,25 @@# frozen_string_literal: trueRSpec.describe BookmarkManager do- let(:user) { Fabricate(:user) }+ subject(:manager) { described_class.new(user) }- let(:reminder_at) { 1.day.from_now }fab!(:post) { Fabricate(:post) }- let(:name) { "Check this out!" }- subject { described_class.new(user) }+ let(:user) { Fabricate(:user) }+ let(:reminder_at) { 1.day.from_now }+ let(:name) { "Check this out!" }describe ".destroy" dolet!(:bookmark) { Fabricate(:bookmark, user: user, bookmarkable: post) }it "deletes the existing bookmark" do- subject.destroy(bookmark.id)+ manager.destroy(bookmark.id)expect(Bookmark.exists?(id: bookmark.id)).to eq(false)endcontext "if the bookmark is the last one bookmarked in the topic" doit "marks the topic user bookmarked column as false" doTopicUser.create(user: user, topic: post.topic, bookmarked: true)- subject.destroy(bookmark.id)+ manager.destroy(bookmark.id)tu = TopicUser.find_by(user: user)expect(tu.bookmarked).to eq(false)end@@ -28,13 +28,13 @@ RSpec.describe BookmarkManager docontext "if the bookmark is belonging to some other user" dolet!(:bookmark) { Fabricate(:bookmark, user: Fabricate(:admin), bookmarkable: post) }it "raises an invalid access error" do- expect { subject.destroy(bookmark.id) }.to raise_error(Discourse::InvalidAccess)+ expect { manager.destroy(bookmark.id) }.to raise_error(Discourse::InvalidAccess)endendcontext "if the bookmark no longer exists" doit "raises a not found error" do- expect { subject.destroy(9999) }.to raise_error(Discourse::NotFound)+ expect { manager.destroy(9999) }.to raise_error(Discourse::NotFound)endendend@@ -53,7 +53,7 @@ RSpec.describe BookmarkManager dolet(:options) { {} }def update_bookmark- subject.update(+ manager.update(bookmark_id: bookmark.id,name: new_name,reminder_at: new_reminder_at,@@ -70,7 +70,7 @@ RSpec.describe BookmarkManager doit "does not reminder_last_sent_at if reminder did not change" dobookmark.update(reminder_last_sent_at: 1.day.ago)- subject.update(bookmark_id: bookmark.id, name: new_name, reminder_at: bookmark.reminder_at)+ manager.update(bookmark_id: bookmark.id, name: new_name, reminder_at: bookmark.reminder_at)bookmark.reloadexpect(bookmark.reminder_last_sent_at).not_to eq(nil)end@@ -112,20 +112,20 @@ RSpec.describe BookmarkManager doendit "destroys all bookmarks for the topic for the specified user" do- subject.destroy_for_topic(topic)+ manager.destroy_for_topic(topic)expect(Bookmark.for_user_in_topic(user.id, topic.id).length).to eq(0)endit "does not destroy any other user's topic bookmarks" douser2 = Fabricate(:user)Fabricate(:bookmark, bookmarkable: Fabricate(:post, topic: topic), user: user2)- subject.destroy_for_topic(topic)+ manager.destroy_for_topic(topic)expect(Bookmark.for_user_in_topic(user2.id, topic.id).length).to eq(1)endit "updates the topic user bookmarked column to false" doTopicUser.create(user: user, topic: topic, bookmarked: true)- subject.destroy_for_topic(topic)+ manager.destroy_for_topic(topic)tu = TopicUser.find_by(user: user)expect(tu.bookmarked).to eq(false)end@@ -176,20 +176,20 @@ RSpec.describe BookmarkManager doit "sets pinned to false if it is true" dobookmark.update(pinned: true)- subject.toggle_pin(bookmark_id: bookmark.id)+ manager.toggle_pin(bookmark_id: bookmark.id)expect(bookmark.reload.pinned).to eq(false)endit "sets pinned to true if it is false" dobookmark.update(pinned: false)- subject.toggle_pin(bookmark_id: bookmark.id)+ manager.toggle_pin(bookmark_id: bookmark.id)expect(bookmark.reload.pinned).to eq(true)endcontext "if the bookmark is belonging to some other user" dolet!(:bookmark) { Fabricate(:bookmark, user: Fabricate(:admin)) }it "raises an invalid access error" do- expect { subject.toggle_pin(bookmark_id: bookmark.id) }.to raise_error(+ expect { manager.toggle_pin(bookmark_id: bookmark.id) }.to raise_error(Discourse::InvalidAccess,)end@@ -198,18 +198,18 @@ RSpec.describe BookmarkManager docontext "if the bookmark no longer exists" dobefore { bookmark.destroy! }it "raises a not found error" do- expect { subject.toggle_pin(bookmark_id: bookmark.id) }.to raise_error(Discourse::NotFound)+ expect { manager.toggle_pin(bookmark_id: bookmark.id) }.to raise_error(Discourse::NotFound)endendenddescribe "#create_for" doit "allows creating a bookmark for the topic and for the first post" do- subject.create_for(bookmarkable_id: post.topic_id, bookmarkable_type: "Topic", name: name)+ manager.create_for(bookmarkable_id: post.topic_id, bookmarkable_type: "Topic", name: name)bookmark = Bookmark.find_by(user: user, bookmarkable: post.topic)expect(bookmark.present?).to eq(true)- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)bookmark = Bookmark.find_by(user: user, bookmarkable: post)expect(bookmark).not_to eq(nil)end@@ -217,26 +217,26 @@ RSpec.describe BookmarkManager doit "when topic is deleted it raises invalid access from guardian check" dopost.topic.trash!expect {- subject.create_for(bookmarkable_id: post.topic_id, bookmarkable_type: "Topic", name: name)+ manager.create_for(bookmarkable_id: post.topic_id, bookmarkable_type: "Topic", name: name)}.to raise_error(Discourse::InvalidAccess)endit "when post is deleted it raises invalid access from guardian check" dopost.trash!expect do- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)end.to raise_error(Discourse::InvalidAccess)endit "adds a validation error when the bookmarkable_type is not registered" do- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "BlahFactory", name: name)- expect(subject.errors.full_messages).to include(+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "BlahFactory", name: name)+ expect(manager.errors.full_messages).to include(I18n.t("bookmarks.errors.invalid_bookmarkable", type: "BlahFactory"),)endit "updates the topic user bookmarked column to true if any post is bookmarked" do- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,@@ -246,14 +246,14 @@ RSpec.describe BookmarkManager doexpect(tu.bookmarked).to eq(true)tu.update(bookmarked: false)new_post = Fabricate(:post, topic: post.topic)- subject.create_for(bookmarkable_id: new_post.id, bookmarkable_type: "Post")+ manager.create_for(bookmarkable_id: new_post.id, bookmarkable_type: "Post")tu.reloadexpect(tu.bookmarked).to eq(true)endit "sets auto_delete_preference to clear_reminder by default" dobookmark =- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,@@ -273,7 +273,7 @@ RSpec.describe BookmarkManager doit "sets auto_delete_preferences to the user's user_option.bookmark_auto_delete_preference" dobookmark =- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,@@ -286,7 +286,7 @@ RSpec.describe BookmarkManager doit "uses the passed in auto_delete_preference option instead of the user's one" dobookmark =- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,@@ -303,7 +303,7 @@ RSpec.describe BookmarkManager docontext "when a reminder time is provided" doit "saves the values correctly" do- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,@@ -322,7 +322,7 @@ RSpec.describe BookmarkManager doendit "saves any additional options successfully" do- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,@@ -339,8 +339,8 @@ RSpec.describe BookmarkManager dobefore { Bookmark.create(bookmarkable: post, user: user) }it "adds an error to the manager" do- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post")- expect(subject.errors.full_messages).to include(+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post")+ expect(manager.errors.full_messages).to include(I18n.t("bookmarks.errors.already_bookmarked", type: "Post"),)end@@ -348,8 +348,8 @@ RSpec.describe BookmarkManager docontext "when the bookmark name is too long" doit "adds an error to the manager" do- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: "test" * 100)- expect(subject.errors.full_messages).to include(+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: "test" * 100)+ expect(manager.errors.full_messages).to include("Name is too long (maximum is 100 characters)",)end@@ -359,13 +359,13 @@ RSpec.describe BookmarkManager dolet(:reminder_at) { 10.days.ago }it "adds an error to the manager" do- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,reminder_at: reminder_at,)- expect(subject.errors.full_messages).to include(+ expect(manager.errors.full_messages).to include(I18n.t("bookmarks.errors.cannot_set_past_reminder"),)end@@ -375,13 +375,13 @@ RSpec.describe BookmarkManager dolet(:reminder_at) { 11.years.from_now }it "adds an error to the manager" do- subject.create_for(+ manager.create_for(bookmarkable_id: post.id,bookmarkable_type: "Post",name: name,reminder_at: reminder_at,)- expect(subject.errors.full_messages).to include(+ expect(manager.errors.full_messages).to include(I18n.t("bookmarks.errors.cannot_set_reminder_in_distant_future"),)end@@ -391,7 +391,7 @@ RSpec.describe BookmarkManager dobefore { post.trash! }it "raises an invalid access error" doexpect {- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)}.to raise_error(Discourse::InvalidAccess)endend@@ -400,7 +400,7 @@ RSpec.describe BookmarkManager dobefore { post.topic.update(category: Fabricate(:private_category, group: Fabricate(:group))) }it "raises an invalid access error" doexpect {- subject.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)+ manager.create_for(bookmarkable_id: post.id, bookmarkable_type: "Post", name: name)}.to raise_error(Discourse::InvalidAccess)endenddiff --git a/spec/lib/bookmark_reminder_notification_handler_spec.rb b/spec/lib/bookmark_reminder_notification_handler_spec.rbindex 9a77ad9bb15..6311d9bf871 100644--- a/spec/lib/bookmark_reminder_notification_handler_spec.rb+++ b/spec/lib/bookmark_reminder_notification_handler_spec.rb@@ -1,19 +1,20 @@# frozen_string_literal: trueRSpec.describe BookmarkReminderNotificationHandler do- subject { described_class }-fab!(:user) { Fabricate(:user) }before { Discourse.redis.flushdb }describe "#send_notification" do+ subject(:send_notification) { handler.send_notification }++ let(:handler) { described_class.new(bookmark) }let!(:bookmark) doFabricate(:bookmark_next_business_day_reminder, user: user, bookmarkable: Fabricate(:post))endit "creates a bookmark reminder notification with the correct details" do- subject.new(bookmark).send_notification+ send_notificationnotif = bookmark.user.notifications.lastexpect(notif.notification_type).to eq(Notification.types[:bookmark_reminder])expect(notif.topic_id).to eq(bookmark.bookmarkable.topic_id)@@ -32,7 +33,7 @@ RSpec.describe BookmarkReminderNotificationHandler doendit "does not send a notification and updates last notification attempt time" do- expect { subject.new(bookmark).send_notification }.not_to change { Notification.count }+ expect { send_notification }.not_to change { Notification.count }expect(bookmark.reload.reminder_last_sent_at).not_to be_blankendend@@ -46,12 +47,12 @@ RSpec.describe BookmarkReminderNotificationHandler doendit "deletes the bookmark after the reminder gets sent" do- subject.new(bookmark).send_notification+ send_notificationexpect(Bookmark.find_by(id: bookmark.id)).to eq(nil)endit "changes the TopicUser bookmarked column to false" do- subject.new(bookmark).send_notification+ send_notificationexpect(TopicUser.find_by(topic: bookmark.bookmarkable.topic, user: user).bookmarked).to eq(false,)@@ -67,7 +68,7 @@ RSpec.describe BookmarkReminderNotificationHandler doendit "does not change the TopicUser bookmarked column to false" do- subject.new(bookmark).send_notification+ send_notificationexpect(TopicUser.find_by(topic: bookmark.bookmarkable.topic, user: user).bookmarked,).to eq(true)@@ -82,7 +83,7 @@ RSpec.describe BookmarkReminderNotificationHandler doendit "resets reminder_at after the reminder gets sent" do- subject.new(bookmark).send_notification+ send_notificationexpect(Bookmark.find_by(id: bookmark.id).reminder_at).to eq(nil)endenddiff --git a/spec/lib/common_passwords/common_passwords_spec.rb b/spec/lib/common_passwords/common_passwords_spec.rbindex 7373882a207..34b8ae20ef7 100644--- a/spec/lib/common_passwords/common_passwords_spec.rb+++ b/spec/lib/common_passwords/common_passwords_spec.rb@@ -6,32 +6,32 @@ RSpec.describe CommonPasswords doenddescribe "#common_password?" do- before { described_class.stubs(:redis).returns(stub_everything) }+ subject(:common_password) { described_class.common_password? @password }- subject { described_class.common_password? @password }+ before { described_class.stubs(:redis).returns(stub_everything) }it "returns false if password isn't in the common passwords list" dodescribed_class.stubs(:password_list).returns(stub_everything(include?: false))@password = "uncommonPassword"- expect(subject).to eq(false)+ expect(common_password).to eq(false)endit "returns false if password is nil" dodescribed_class.expects(:password_list).never@password = nil- expect(subject).to eq(false)+ expect(common_password).to eq(false)endit "returns false if password is blank" dodescribed_class.expects(:password_list).never@password = ""- expect(subject).to eq(false)+ expect(common_password).to eq(false)endit "returns true if password is in the common passwords list" dodescribed_class.stubs(:password_list).returns(stub_everything(include?: true))@password = "password"- expect(subject).to eq(true)+ expect(common_password).to eq(true)endenddiff --git a/spec/lib/discourse_updates_spec.rb b/spec/lib/discourse_updates_spec.rbindex efbb2467af3..6e1f30d2f31 100644--- a/spec/lib/discourse_updates_spec.rb+++ b/spec/lib/discourse_updates_spec.rb@@ -8,7 +8,7 @@ RSpec.describe DiscourseUpdates doDiscourseUpdates.updated_at = updated_atend- subject { DiscourseUpdates.check_version }+ subject(:version) { DiscourseUpdates.check_version }context "when version check was done at the current installed version" dobefore { DiscourseUpdates.last_installed_version = Discourse::VERSION::STRING }@@ -19,15 +19,15 @@ RSpec.describe DiscourseUpdates dobefore { stub_data(Discourse::VERSION::STRING, 0, false, time) }it "returns all the version fields" do- expect(subject.latest_version).to eq(Discourse::VERSION::STRING)- expect(subject.missing_versions_count).to eq(0)- expect(subject.critical_updates).to eq(false)- expect(subject.installed_version).to eq(Discourse::VERSION::STRING)- expect(subject.stale_data).to eq(false)+ expect(version.latest_version).to eq(Discourse::VERSION::STRING)+ expect(version.missing_versions_count).to eq(0)+ expect(version.critical_updates).to eq(false)+ expect(version.installed_version).to eq(Discourse::VERSION::STRING)+ expect(version.stale_data).to eq(false)endit "returns the timestamp of the last version check" do- expect(subject.updated_at).to be_within_one_second_of(time)+ expect(version.updated_at).to be_within_one_second_of(time)endend@@ -36,14 +36,14 @@ RSpec.describe DiscourseUpdates dobefore { stub_data("0.9.0", 2, false, time) }it "returns all the version fields" do- expect(subject.latest_version).to eq("0.9.0")- expect(subject.missing_versions_count).to eq(2)- expect(subject.critical_updates).to eq(false)- expect(subject.installed_version).to eq(Discourse::VERSION::STRING)+ expect(version.latest_version).to eq("0.9.0")+ expect(version.missing_versions_count).to eq(2)+ expect(version.critical_updates).to eq(false)+ expect(version.installed_version).to eq(Discourse::VERSION::STRING)endit "returns the timestamp of the last version check" do- expect(subject.updated_at).to be_within_one_second_of(time)+ expect(version.updated_at).to be_within_one_second_of(time)endendend@@ -52,22 +52,22 @@ RSpec.describe DiscourseUpdates dobefore { stub_data(nil, nil, false, nil) }it "returns the installed version" do- expect(subject.installed_version).to eq(Discourse::VERSION::STRING)+ expect(version.installed_version).to eq(Discourse::VERSION::STRING)endit "indicates that version check has not been performed" do- expect(subject.updated_at).to eq(nil)- expect(subject.stale_data).to eq(true)+ expect(version.updated_at).to eq(nil)+ expect(version.stale_data).to eq(true)endit "does not return latest version info" do- expect(subject.latest_version).to eq(nil)- expect(subject.missing_versions_count).to eq(nil)- expect(subject.critical_updates).to eq(nil)+ expect(version.latest_version).to eq(nil)+ expect(version.missing_versions_count).to eq(nil)+ expect(version.critical_updates).to eq(nil)endit "queues a version check" do- expect_enqueued_with(job: :version_check) { subject }+ expect_enqueued_with(job: :version_check) { version }endend@@ -76,15 +76,15 @@ RSpec.describe DiscourseUpdates docontext "with old version check data" doshared_examples "queue version check and report that version is ok" doit "queues a version check" do- expect_enqueued_with(job: :version_check) { subject }+ expect_enqueued_with(job: :version_check) { version }endit "reports 0 missing versions" do- expect(subject.missing_versions_count).to eq(0)+ expect(version.missing_versions_count).to eq(0)endit "reports that a version check will be run soon" do- expect(subject.version_check_pending).to eq(true)+ expect(version.version_check_pending).to eq(true)endend@@ -105,15 +105,15 @@ RSpec.describe DiscourseUpdates doshared_examples "when last_installed_version is old" doit "queues a version check" do- expect_enqueued_with(job: :version_check) { subject }+ expect_enqueued_with(job: :version_check) { version }endit "reports 0 missing versions" do- expect(subject.missing_versions_count).to eq(0)+ expect(version.missing_versions_count).to eq(0)endit "reports that a version check will be run soon" do- expect(subject.version_check_pending).to eq(true)+ expect(version.version_check_pending).to eq(true)endenddiff --git a/spec/lib/email/message_builder_spec.rb b/spec/lib/email/message_builder_spec.rbindex 567f4b5a922..3be2744da14 100644--- a/spec/lib/email/message_builder_spec.rb+++ b/spec/lib/email/message_builder_spec.rb@@ -4,9 +4,9 @@ require "email/message_builder"RSpec.describe Email::MessageBuilder dolet(:to_address) { "[email protected]" }- let(:subject) { "Tree Trunks has made some apple pie!" }+ let(:email_subject) { "Tree Trunks has made some apple pie!" }let(:body) { "oh my glob Jake, Tree Trunks just made the tastiest apple pie ever!" }- let(:builder) { Email::MessageBuilder.new(to_address, subject: subject, body: body) }+ let(:builder) { Email::MessageBuilder.new(to_address, subject: email_subject, body: body) }let(:build_args) { builder.build_args }let(:header_args) { builder.header_args }let(:allow_reply_header) { described_class::ALLOW_REPLY_BY_EMAIL_HEADER }@@ -16,7 +16,7 @@ RSpec.describe Email::MessageBuilder doendit "has the subject" do- expect(builder.subject).to eq(subject)+ expect(builder.subject).to eq(email_subject)endit "has the body" dodiff --git a/spec/lib/final_destination/ssrf_detector_spec.rb b/spec/lib/final_destination/ssrf_detector_spec.rbindex 8479f8bf159..8781390507d 100644--- a/spec/lib/final_destination/ssrf_detector_spec.rb+++ b/spec/lib/final_destination/ssrf_detector_spec.rb@@ -6,8 +6,8 @@ describe FinalDestination::SSRFDetector doSiteSetting.blocked_ip_blocks = "13.134.89.0/24|73.234.19.0/30\n"SiteSetting.allowed_internal_hosts = "awesomesauce.com\n|goodbye.net"- expect(subject.blocked_ip_blocks).to eq(%w[13.134.89.0/24 73.234.19.0/30])- expect(subject.allowed_internal_hosts).to eq(+ expect(described_class.blocked_ip_blocks).to eq(%w[13.134.89.0/24 73.234.19.0/30])+ expect(described_class.allowed_internal_hosts).to eq(["test.localhost", # Discourse.base_url"awesomesauce.com",@@ -20,8 +20,8 @@ describe FinalDestination::SSRFDetector doSiteSetting.blocked_ip_blocks = "13.134.89.0/24\n73.234.19.0/30\n\n"SiteSetting.allowed_internal_hosts = "awesomesauce.com\n\ngoodbye.net\n\n"- expect(subject.blocked_ip_blocks).to eq(%w[13.134.89.0/24 73.234.19.0/30])- expect(subject.allowed_internal_hosts).to eq(+ expect(described_class.blocked_ip_blocks).to eq(%w[13.134.89.0/24 73.234.19.0/30])+ expect(described_class.allowed_internal_hosts).to eq(["test.localhost", # Discourse.base_url"awesomesauce.com",@@ -32,90 +32,90 @@ describe FinalDestination::SSRFDetector doit "ignores invalid IP blocks" doSiteSetting.blocked_ip_blocks = "2001:abc:de::/48|notanip"- expect(subject.blocked_ip_blocks).to eq(%w[2001:abc:de::/48])+ expect(described_class.blocked_ip_blocks).to eq(%w[2001:abc:de::/48])endenddescribe ".ip_allowed?" doit "returns false for blocked IPs" doSiteSetting.blocked_ip_blocks = "98.0.0.0/8|78.13.47.0/24|9001:82f3::/32"- expect(subject.ip_allowed?("98.23.19.111")).to eq(false)- expect(subject.ip_allowed?("9001:82f3:8873::3")).to eq(false)+ expect(described_class.ip_allowed?("98.23.19.111")).to eq(false)+ expect(described_class.ip_allowed?("9001:82f3:8873::3")).to eq(false)end%w[0.0.0.0 10.0.0.0 127.0.0.0 172.31.100.31 255.255.255.255 ::1 ::].each do |internal_ip|it "returns false for '#{internal_ip}'" do- expect(subject.ip_allowed?(internal_ip)).to eq(false)+ expect(described_class.ip_allowed?(internal_ip)).to eq(false)endendit "returns false for private IPv4-mapped IPv6 addresses" do- expect(subject.ip_allowed?("::ffff:172.31.100.31")).to eq(false)- expect(subject.ip_allowed?("::ffff:0.0.0.0")).to eq(false)+ expect(described_class.ip_allowed?("::ffff:172.31.100.31")).to eq(false)+ expect(described_class.ip_allowed?("::ffff:0.0.0.0")).to eq(false)endit "returns true for public IPv4-mapped IPv6 addresses" do- expect(subject.ip_allowed?("::ffff:52.52.167.244")).to eq(true)+ expect(described_class.ip_allowed?("::ffff:52.52.167.244")).to eq(true)endenddescribe ".host_bypasses_checks?" doit "returns true for URLs when allowed_internal_hosts allows the host" doSiteSetting.allowed_internal_hosts = "allowedhost1.com|allowedhost2.com"- expect(subject.host_bypasses_checks?("allowedhost1.com")).to eq(true)- expect(subject.host_bypasses_checks?("allowedhost2.com")).to eq(true)+ expect(described_class.host_bypasses_checks?("allowedhost1.com")).to eq(true)+ expect(described_class.host_bypasses_checks?("allowedhost2.com")).to eq(true)endit "returns false for other hosts" do- expect(subject.host_bypasses_checks?("otherhost.com")).to eq(false)+ expect(described_class.host_bypasses_checks?("otherhost.com")).to eq(false)endit "returns true for the base uri" doSiteSetting.force_hostname = "final-test.example.com"- expect(subject.host_bypasses_checks?("final-test.example.com")).to eq(true)+ expect(described_class.host_bypasses_checks?("final-test.example.com")).to eq(true)endit "returns true for the S3 CDN url" doSiteSetting.enable_s3_uploads = trueSiteSetting.s3_cdn_url = "https://s3.example.com"- expect(subject.host_bypasses_checks?("s3.example.com")).to eq(true)+ expect(described_class.host_bypasses_checks?("s3.example.com")).to eq(true)endit "returns true for the CDN url" doGlobalSetting.stubs(:cdn_url).returns("https://cdn.example.com/discourse")- expect(subject.host_bypasses_checks?("cdn.example.com")).to eq(true)+ expect(described_class.host_bypasses_checks?("cdn.example.com")).to eq(true)endenddescribe ".lookup_and_filter_ips" doit "returns a fake response in tests" do- expect(subject.lookup_and_filter_ips("example.com")).to eq(["1.2.3.4"])+ expect(described_class.lookup_and_filter_ips("example.com")).to eq(["1.2.3.4"])endit "correctly filters private and blocked IPs" doSiteSetting.blocked_ip_blocks = "9.10.11.12/24"- subject.stubs(:lookup_ips).returns(%w[127.0.0.1 5.6.7.8 9.10.11.12])- expect(subject.lookup_and_filter_ips("example.com")).to eq(["5.6.7.8"])+ described_class.stubs(:lookup_ips).returns(%w[127.0.0.1 5.6.7.8 9.10.11.12])+ expect(described_class.lookup_and_filter_ips("example.com")).to eq(["5.6.7.8"])endit "raises an exception if all IPs are blocked" do- subject.stubs(:lookup_ips).returns(["127.0.0.1"])- expect { subject.lookup_and_filter_ips("example.com") }.to raise_error(- subject::DisallowedIpError,+ described_class.stubs(:lookup_ips).returns(["127.0.0.1"])+ expect { described_class.lookup_and_filter_ips("example.com") }.to raise_error(+ described_class::DisallowedIpError,)endit "raises an exception if lookup fails" do- subject.stubs(:lookup_ips).raises(SocketError)- expect { subject.lookup_and_filter_ips("example.com") }.to raise_error(- subject::LookupFailedError,+ described_class.stubs(:lookup_ips).raises(SocketError)+ expect { described_class.lookup_and_filter_ips("example.com") }.to raise_error(+ described_class::LookupFailedError,)endit "bypasses filtering for allowlisted hosts" doSiteSetting.allowed_internal_hosts = "example.com"- subject.stubs(:lookup_ips).returns(["127.0.0.1"])- expect(subject.lookup_and_filter_ips("example.com")).to eq(["127.0.0.1"])+ described_class.stubs(:lookup_ips).returns(["127.0.0.1"])+ expect(described_class.lookup_and_filter_ips("example.com")).to eq(["127.0.0.1"])endendenddiff --git a/spec/lib/imap/sync_spec.rb b/spec/lib/imap/sync_spec.rbindex 991ab4c38f4..b993e157f3a 100644--- a/spec/lib/imap/sync_spec.rb+++ b/spec/lib/imap/sync_spec.rb@@ -39,14 +39,14 @@ RSpec.describe Imap::Sync dodescribe "no previous sync" dolet(:from) { "[email protected]" }- let(:subject) { "Testing email post" }+ let(:email_subject) { "Testing email post" }let(:message_id) { "#{SecureRandom.hex}@example.com" }let(:email) doEmailFabricator(from: from,to: group.email_username,- subject: subject,+ subject: email_subject,message_id: message_id,)end@@ -80,7 +80,7 @@ RSpec.describe Imap::Sync doexpect(group.imap_last_uid).to eq(100)topic = Topic.last- expect(topic.title).to eq(subject)+ expect(topic.title).to eq(email_subject)expect(topic.user.email).to eq(from)expect(topic.tags.pluck(:name)).to contain_exactly("seen", "important", "test-label")@@ -110,7 +110,7 @@ RSpec.describe Imap::Sync doexpect(group.imap_last_uid).to eq(100)topic = Topic.last- expect(topic.title).to eq(subject)+ expect(topic.title).to eq(email_subject)expect(topic.user.email).to eq(from)expect(topic.tags).to eq([])end@@ -161,7 +161,7 @@ RSpec.describe Imap::Sync doenddescribe "previous sync" do- let(:subject) { "Testing email post" }+ let(:email_subject) { "Testing email post" }let(:first_from) { "[email protected]" }let(:first_message_id) { SecureRandom.hex }@@ -191,7 +191,7 @@ RSpec.describe Imap::Sync dofrom: first_from,to: group.email_username,cc: second_from,- subject: subject,+ subject: email_subject,body: first_body,),},@@ -203,7 +203,7 @@ RSpec.describe Imap::Sync do}.by(1).and change { IncomingEmail.count }.by(1)topic = Topic.last- expect(topic.title).to eq(subject)+ expect(topic.title).to eq(email_subject)expect(GroupArchivedMessage.where(topic_id: topic.id).exists?).to eq(false)post = Post.where(post_type: Post.types[:regular]).last@@ -233,7 +233,7 @@ RSpec.describe Imap::Sync doin_reply_to: first_message_id,from: second_from,to: group.email_username,- subject: "Re: #{subject}",+ subject: "Re: #{email_subject}",body: second_body,),},@@ -267,7 +267,7 @@ RSpec.describe Imap::Sync do}.and not_change { IncomingEmail.count }topic = Topic.last- expect(topic.title).to eq(subject)+ expect(topic.title).to eq(email_subject)expect(GroupArchivedMessage.where(topic_id: topic.id).exists?).to eq(true)expect(Topic.last.posts.where(post_type: Post.types[:regular]).count).to eq(2)@@ -294,7 +294,7 @@ RSpec.describe Imap::Sync dofrom: first_from,to: group.email_username,cc: second_from,- subject: subject,+ subject: email_subject,body: first_body,),},@@ -389,7 +389,7 @@ RSpec.describe Imap::Sync dofrom: first_from,to: group.email_username,cc: second_from,- subject: subject,+ subject: email_subject,body: first_body,),},@@ -446,7 +446,7 @@ RSpec.describe Imap::Sync dofrom: first_from,to: group.email_username,cc: second_from,- subject: subject,+ subject: email_subject,body: first_body,),},@@ -494,7 +494,7 @@ RSpec.describe Imap::Sync doenddescribe "invalidated previous sync" do- let(:subject) { "Testing email post" }+ let(:email_subject) { "Testing email post" }let(:first_from) { "[email protected]" }let(:first_message_id) { SecureRandom.hex }@@ -526,7 +526,7 @@ RSpec.describe Imap::Sync dofrom: first_from,to: group.email_username,cc: second_from,- subject: subject,+ subject: email_subject,body: first_body,),},@@ -540,7 +540,7 @@ RSpec.describe Imap::Sync doin_reply_to: first_message_id,from: second_from,to: group.email_username,- subject: "Re: #{subject}",+ subject: "Re: #{email_subject}",body: second_body,),},@@ -571,7 +571,7 @@ RSpec.describe Imap::Sync dofrom: first_from,to: group.email_username,cc: second_from,- subject: subject,+ subject: email_subject,body: first_body,),},@@ -585,7 +585,7 @@ RSpec.describe Imap::Sync doin_reply_to: first_message_id,from: second_from,to: group.email_username,- subject: "Re: #{subject}",+ subject: "Re: #{email_subject}",body: second_body,),},diff --git a/spec/lib/message_id_service_spec.rb b/spec/lib/message_id_service_spec.rbindex 271bed77064..d51750aa3e2 100644--- a/spec/lib/message_id_service_spec.rb+++ b/spec/lib/message_id_service_spec.rb@@ -5,18 +5,16 @@ RSpec.describe Email::MessageIdService dofab!(:post) { Fabricate(:post, topic: topic) }fab!(:second_post) { Fabricate(:post, topic: topic) }- subject { described_class }-describe "#generate_or_use_existing" doit "does not override a post's existing outbound_message_id" dopost.update!(outbound_message_id: "[email protected]")- result = subject.generate_or_use_existing(post.id)+ result = described_class.generate_or_use_existing(post.id)expect(result).to eq(["<[email protected]>"])endit "generates an outbound_message_id in the correct format if it's blank for the post" dopost.update!(outbound_message_id: nil)- result = subject.generate_or_use_existing(post.id)+ result = described_class.generate_or_use_existing(post.id)expect(result).to eq(["<discourse/post/#{post.id}@#{Email::MessageIdService.host}>"])end@@ -39,7 +37,7 @@ RSpec.describe Email::MessageIdService do)post_bulk4 = Fabricate(:post, topic: topic, created_at: 3.days.ago, outbound_message_id: nil)result =- subject.generate_or_use_existing(+ described_class.generate_or_use_existing([post_bulk1.id, post_bulk2.id, post_bulk3.id, post_bulk4.id],)expect(result).to eq(@@ -63,36 +61,43 @@ RSpec.describe Email::MessageIdService doendit "finds a post based only on a post-format message id" do- expect(subject.find_post_from_message_ids([post_format_message_id])).to eq(post)+ expect(described_class.find_post_from_message_ids([post_format_message_id])).to eq(post)endit "finds a post based only on a topic-format message id" do- expect(subject.find_post_from_message_ids([topic_format_message_id])).to eq(post)+ expect(described_class.find_post_from_message_ids([topic_format_message_id])).to eq(post)endit "finds a post based only on a discourse-format message id" do- expect(subject.find_post_from_message_ids([discourse_format_message_id])).to eq(post)+ expect(described_class.find_post_from_message_ids([discourse_format_message_id])).to eq(post)endit "finds a post from the post's outbound_message_id" do- post.update!(outbound_message_id: subject.message_id_clean(discourse_format_message_id))- expect(subject.find_post_from_message_ids([discourse_format_message_id])).to eq(post)+ post.update!(+ outbound_message_id: described_class.message_id_clean(discourse_format_message_id),+ )+ expect(described_class.find_post_from_message_ids([discourse_format_message_id])).to eq(post)endit "finds a post from the email log" doemail_log =- Fabricate(:email_log, message_id: subject.message_id_clean(default_format_message_id))- expect(subject.find_post_from_message_ids([default_format_message_id])).to eq(email_log.post)+ Fabricate(+ :email_log,+ message_id: described_class.message_id_clean(default_format_message_id),+ )+ expect(described_class.find_post_from_message_ids([default_format_message_id])).to eq(+ email_log.post,+ )endit "finds a post from the incoming email log" doincoming_email =Fabricate(:incoming_email,- message_id: subject.message_id_clean(gmail_format_message_id),+ message_id: described_class.message_id_clean(gmail_format_message_id),post: Fabricate(:post),)- expect(subject.find_post_from_message_ids([gmail_format_message_id])).to eq(+ expect(described_class.find_post_from_message_ids([gmail_format_message_id])).to eq(incoming_email.post,)end@@ -101,16 +106,16 @@ RSpec.describe Email::MessageIdService doincoming_email =Fabricate(:incoming_email,- message_id: subject.message_id_clean(post_format_message_id),+ message_id: described_class.message_id_clean(post_format_message_id),post: Fabricate(:post, created_at: 10.days.ago),)- expect(subject.find_post_from_message_ids([post_format_message_id])).to eq(post)+ expect(described_class.find_post_from_message_ids([post_format_message_id])).to eq(post)endenddescribe "#discourse_generated_message_id?" dodef check_format(message_id)- subject.discourse_generated_message_id?(message_id)+ described_class.discourse_generated_message_id?(message_id)endit "works correctly for the different possible formats" dodiff --git a/spec/lib/onebox/engine/google_maps_onebox_spec.rb b/spec/lib/onebox/engine/google_maps_onebox_spec.rbindex 4ccecf62ef5..fab528a6799 100644--- a/spec/lib/onebox/engine/google_maps_onebox_spec.rb+++ b/spec/lib/onebox/engine/google_maps_onebox_spec.rb@@ -53,17 +53,8 @@ RSpec.describe Onebox::Engine::GoogleMapsOnebox do}# Register URL redirects- before do- URLS.values.each do |t|- status, location = *t[:redirect]- location = URLS[location][:test] if location.is_a? Symbol-- stub_request(:head, t[:test]).to_return(status: status, headers: { location: location })- end- end-# Prevent sleep from wasting our time when we test with strange redirects- subject do+ subject(:onebox) dodescribed_class.send(:allocate).tap do |obj|@@ -72,17 +63,26 @@ RSpec.describe Onebox::Engine::GoogleMapsOnebox doendend- let(:data) { Onebox::Helpers.symbolize_keys(subject.send(:data)) }+ before do+ URLS.values.each do |t|+ status, location = *t[:redirect]+ location = URLS[location][:test] if location.is_a? Symbol++ stub_request(:head, t[:test]).to_return(status: status, headers: { location: location })+ end+ end++ let(:data) { Onebox::Helpers.symbolize_keys(onebox.send(:data)) }let(:link) { |example| URLS[example.metadata[:urltype] || :short][:test] }include_context "an engine", urltype: :shortURLS.each do |kind, t|it "processes #{kind.to_s} url correctly", urltype: kind do- expect(subject.url).to eq t[:expect]- expect(subject.streetview?).to t[:streetview] ? be_truthy : be_falsey- expect(subject.to_html).to include("<iframe")- expect(subject.placeholder_html).to include("placeholder-icon map")+ expect(onebox.url).to eq t[:expect]+ expect(onebox.streetview?).to t[:streetview] ? be_truthy : be_falsey+ expect(onebox.to_html).to include("<iframe")+ expect(onebox.placeholder_html).to include("placeholder-icon map")endendenddiff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rbindex 2957b94cab2..e08b5f67f09 100644--- a/spec/lib/plugin/instance_spec.rb+++ b/spec/lib/plugin/instance_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe Plugin::Instance do+ subject(:plugin_instance) { described_class.new }+after { DiscoursePluginRegistry.reset! }describe "find_all" do@@ -601,7 +603,7 @@ RSpec.describe Plugin::Instance dohighest_flag_id = ReviewableScore.types.values.maxflag_name = :new_flag- subject.replace_flags(settings: original_flags) do |settings, next_flag_id|+ plugin_instance.replace_flags(settings: original_flags) do |settings, next_flag_id|settings.add(next_flag_id, flag_name)end@@ -613,7 +615,7 @@ RSpec.describe Plugin::Instance dohighest_flag_id = ReviewableScore.types.values.maxnew_score_type = :new_score_type- subject.replace_flags(+ plugin_instance.replace_flags(settings: original_flags,score_type_names: [new_score_type],) { |settings, next_flag_id| settings.add(next_flag_id, :new_flag) }@@ -629,7 +631,7 @@ RSpec.describe Plugin::Instance doit "adds a custom api key scope" doactions = %w[admin/groups#create]- subject.add_api_key_scope(:groups, create: { actions: actions })+ plugin_instance.add_api_key_scope(:groups, create: { actions: actions })expect(ApiKeyScope.scope_mappings.dig(:groups, :create, :actions)).to contain_exactly(*actions,diff --git a/spec/lib/post_destroyer_spec.rb b/spec/lib/post_destroyer_spec.rbindex e1bc124fdf5..2733138add0 100644--- a/spec/lib/post_destroyer_spec.rb+++ b/spec/lib/post_destroyer_spec.rb@@ -735,20 +735,20 @@ RSpec.describe PostDestroyer doendcontext "as an admin" do- subject { PostDestroyer.new(admin, post).destroy }+ subject(:destroyer) { PostDestroyer.new(admin, post).destroy }it "deletes the post" do- subject+ destroyerexpect(post.deleted_at).to be_presentexpect(post.deleted_by).to eq(admin)endit "creates a new user history entry" do- expect { subject }.to change { UserHistory.count }.by(1)+ expect { destroyer }.to change { UserHistory.count }.by(1)endit "triggers a extensibility event" do- events = DiscourseEvent.track_events { subject }+ events = DiscourseEvent.track_events { destroyer }expect(events[0][:event_name]).to eq(:post_destroyed)expect(events[0][:params].first).to eq(post)@@ -768,34 +768,34 @@ RSpec.describe PostDestroyer doendcontext "as a moderator" do- subject { PostDestroyer.new(moderator, reply).destroy }+ subject(:destroyer) { PostDestroyer.new(moderator, reply).destroy }it "deletes the reply" do- subject+ destroyerexpect(reply.deleted_at).to be_presentexpect(reply.deleted_by).to eq(moderator)endit "doesn't decrement post_count again" do- expect { subject }.to_not change { author.user_stat.post_count }+ expect { destroyer }.to_not change { author.user_stat.post_count }endendcontext "as an admin" do- subject { PostDestroyer.new(admin, reply).destroy }+ subject(:destroyer) { PostDestroyer.new(admin, reply).destroy }it "deletes the post" do- subject+ destroyerexpect(reply.deleted_at).to be_presentexpect(reply.deleted_by).to eq(admin)endit "doesn't decrement post_count again" do- expect { subject }.to_not change { author.user_stat.post_count }+ expect { destroyer }.to_not change { author.user_stat.post_count }endit "creates a new user history entry" do- expect { subject }.to change { UserHistory.count }.by(1)+ expect { destroyer }.to change { UserHistory.count }.by(1)endendenddiff --git a/spec/lib/post_jobs_enqueuer_spec.rb b/spec/lib/post_jobs_enqueuer_spec.rbindex 3a66a3ab4dc..266c4f8b0de 100644--- a/spec/lib/post_jobs_enqueuer_spec.rb+++ b/spec/lib/post_jobs_enqueuer_spec.rb@@ -1,13 +1,13 @@# frozen_string_literal: trueRSpec.describe PostJobsEnqueuer do+ subject(:enqueuer) { described_class.new(post, topic, new_topic, opts) }+let!(:post) { Fabricate(:post, topic: topic) }let!(:topic) { Fabricate(:topic) }let(:new_topic) { false }let(:opts) { { post_alert_options: {} } }- subject { described_class.new(post, topic, new_topic, opts) }-context "for regular topics" doit "enqueues the :post_alert job" doexpect_enqueued_with(@@ -17,24 +17,24 @@ RSpec.describe PostJobsEnqueuer donew_record: true,options: opts[:post_alert_options],},- ) { subject.enqueue_jobs }+ ) { enqueuer.enqueue_jobs }endit "enqueues the :notify_mailing_list_subscribers job" doexpect_enqueued_with(job: :notify_mailing_list_subscribers, args: { post_id: post.id }) do- subject.enqueue_jobs+ enqueuer.enqueue_jobsendendit "enqueues the :post_update_topic_tracking_state job" doexpect_enqueued_with(job: :post_update_topic_tracking_state, args: { post_id: post.id }) do- subject.enqueue_jobs+ enqueuer.enqueue_jobsendendit "enqueues the :feature_topic_users job" doexpect_enqueued_with(job: :feature_topic_users, args: { topic_id: topic.id }) do- subject.enqueue_jobs+ enqueuer.enqueue_jobsendend@@ -44,7 +44,7 @@ RSpec.describe PostJobsEnqueuer doit "calls the correct topic tracking state class to publish_new" doTopicTrackingState.expects(:publish_new).with(topic)PrivateMessageTopicTrackingState.expects(:publish_new).never- subject.enqueue_jobs+ enqueuer.enqueue_jobsendendend@@ -54,19 +54,19 @@ RSpec.describe PostJobsEnqueuer doit "does not enqueue the :notify_mailing_list_subscribers job" doexpect_not_enqueued_with(job: :notify_mailing_list_subscribers, args: { post_id: post.id }) do- subject.enqueue_jobs+ enqueuer.enqueue_jobsendendit "enqueues the :post_update_topic_tracking_state job" doexpect_enqueued_with(job: :post_update_topic_tracking_state, args: { post_id: post.id }) do- subject.enqueue_jobs+ enqueuer.enqueue_jobsendendit "enqueues the :feature_topic_users job" doexpect_enqueued_with(job: :feature_topic_users, args: { topic_id: topic.id }) do- subject.enqueue_jobs+ enqueuer.enqueue_jobsendend@@ -76,7 +76,7 @@ RSpec.describe PostJobsEnqueuer doit "calls the correct topic tracking state class to publish_new" doTopicTrackingState.expects(:publish_new).neverPrivateMessageTopicTrackingState.expects(:publish_new).with(topic)- subject.enqueue_jobs+ enqueuer.enqueue_jobsendend@@ -99,7 +99,7 @@ RSpec.describe PostJobsEnqueuer doargs: {topic_id: topic.id,},- ) { subject.enqueue_jobs }+ ) { enqueuer.enqueue_jobs }endendenddiff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rbindex c04805aa6cb..83a471798d3 100644--- a/spec/lib/post_revisor_spec.rb+++ b/spec/lib/post_revisor_spec.rb@@ -197,9 +197,9 @@ RSpec.describe PostRevisor doenddescribe "editing tags" do- fab!(:post) { Fabricate(:post) }+ subject(:post_revisor) { PostRevisor.new(post) }- subject { PostRevisor.new(post) }+ fab!(:post) { Fabricate(:post) }before doJobs.run_immediately!@@ -212,19 +212,21 @@ RSpec.describe PostRevisor doendit "creates notifications" do- expect { subject.revise!(admin, tags: ["new-tag"]) }.to change { Notification.count }.by(1)+ expect { post_revisor.revise!(admin, tags: ["new-tag"]) }.to change { Notification.count }.by(+ 1,+ )endit "skips notifications if disable_tags_edit_notifications" doSiteSetting.disable_tags_edit_notifications = true- expect { subject.revise!(admin, tags: ["new-tag"]) }.not_to change { Notification.count }+ expect { post_revisor.revise!(admin, tags: ["new-tag"]) }.not_to change { Notification.count }endit "doesn't create a small_action post when create_post_for_category_and_tag_changes is false" doSiteSetting.create_post_for_category_and_tag_changes = false- expect { subject.revise!(admin, tags: ["new-tag"]) }.not_to change { Post.count }+ expect { post_revisor.revise!(admin, tags: ["new-tag"]) }.not_to change { Post.count }enddescribe "when `create_post_for_category_and_tag_changes` site setting is enabled" do@@ -236,7 +238,7 @@ RSpec.describe PostRevisor doit "Creates a small_action post with correct translation when both adding and removing tags" dopost.topic.update!(tags: [tag1])- expect { subject.revise!(admin, tags: [tag2.name]) }.to change {+ expect { post_revisor.revise!(admin, tags: [tag2.name]) }.to change {Post.where(topic_id: post.topic_id, action_code: "tags_changed").count}.by(1)@@ -252,7 +254,7 @@ RSpec.describe PostRevisor doit "Creates a small_action post with correct translation when adding tags" dopost.topic.update!(tags: [])- expect { subject.revise!(admin, tags: [tag1.name]) }.to change {+ expect { post_revisor.revise!(admin, tags: [tag1.name]) }.to change {Post.where(topic_id: post.topic_id, action_code: "tags_changed").count}.by(1)@@ -264,7 +266,7 @@ RSpec.describe PostRevisor doit "Creates a small_action post with correct translation when removing tags" dopost.topic.update!(tags: [tag1, tag2])- expect { subject.revise!(admin, tags: []) }.to change {+ expect { post_revisor.revise!(admin, tags: []) }.to change {Post.where(topic_id: post.topic_id, action_code: "tags_changed").count}.by(1)@@ -277,7 +279,7 @@ RSpec.describe PostRevisor docurrent_category = post.topic.categorycategory = Fabricate(:category)- expect { subject.revise!(admin, category_id: category.id) }.to change {+ expect { post_revisor.revise!(admin, category_id: category.id) }.to change {Post.where(topic_id: post.topic_id, action_code: "category_changed").count}.by(1)@@ -310,24 +312,24 @@ RSpec.describe PostRevisor doenddescribe "revise" do+ subject(:post_revisor) { PostRevisor.new(post) }+let(:post) { Fabricate(:post, post_args) }let(:first_version_at) { post.last_version_at }- subject { PostRevisor.new(post) }-it "destroys last revision if edit is undone" doold_raw = post.raw- subject.revise!(admin, raw: "new post body", tags: ["new-tag"])+ post_revisor.revise!(admin, raw: "new post body", tags: ["new-tag"])expect(post.topic.reload.tags.map(&:name)).to contain_exactly("new-tag")expect(post.post_revisions.reload.size).to eq(1)- expect(subject.raw_changed?).to eq(true)+ expect(post_revisor.raw_changed?).to eq(true)- subject.revise!(admin, raw: old_raw, tags: [])+ post_revisor.revise!(admin, raw: old_raw, tags: [])expect(post.topic.reload.tags.map(&:name)).to be_emptyexpect(post.post_revisions.reload.size).to eq(0)- subject.revise!(admin, raw: "next post body", tags: ["new-tag"])+ post_revisor.revise!(admin, raw: "next post body", tags: ["new-tag"])expect(post.topic.reload.tags.map(&:name)).to contain_exactly("new-tag")expect(post.post_revisions.reload.size).to eq(1)end@@ -335,7 +337,7 @@ RSpec.describe PostRevisor dodescribe "with the same body" doit "doesn't change version" doexpect {- expect(subject.revise!(post.user, raw: post.raw)).to eq(false)+ expect(post_revisor.revise!(post.user, raw: post.raw)).to eq(false)post.reload}.not_to change(post, :version)end@@ -344,7 +346,7 @@ RSpec.describe PostRevisor dodescribe "with nil raw contents" doit "doesn't change version" doexpect {- expect(subject.revise!(post.user, raw: nil)).to eq(false)+ expect(post_revisor.revise!(post.user, raw: nil)).to eq(false)post.reload}.not_to change(post, :version)end@@ -354,7 +356,7 @@ RSpec.describe PostRevisor dobefore { topic.update!(slow_mode_seconds: 1000) }it "regular edits are not allowed by default" do- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + 1000.minutes,@@ -368,7 +370,7 @@ RSpec.describe PostRevisor doit "grace period editing is allowed" doSiteSetting.editing_grace_period = 1.minute- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + 10.seconds,@@ -381,7 +383,7 @@ RSpec.describe PostRevisor doit "regular edits are allowed if it was turned on in settings" doSiteSetting.slow_mode_prevents_editing = false- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + 10.minutes,@@ -393,7 +395,11 @@ RSpec.describe PostRevisor doit "staff is allowed to edit posts even if the topic is in slow mode" doadmin = Fabricate(:admin)- subject.revise!(admin, { raw: "updated body" }, revised_at: post.updated_at + 10.minutes)+ post_revisor.revise!(+ admin,+ { raw: "updated body" },+ revised_at: post.updated_at + 10.minutes,+ )post.reloadexpect(post.errors).to be_empty@@ -404,7 +410,7 @@ RSpec.describe PostRevisor doit "correctly applies edits" doSiteSetting.editing_grace_period = 1.minute- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + 10.seconds,@@ -415,7 +421,7 @@ RSpec.describe PostRevisor doexpect(post.public_version).to eq(1)expect(post.revisions.size).to eq(0)expect(post.last_version_at).to eq_time(first_version_at)- expect(subject.category_changed).to be_blank+ expect(post_revisor.category_changed).to be_blankendit "does create a new version if a large diff happens" do@@ -486,13 +492,13 @@ RSpec.describe PostRevisor doSiteSetting.editing_grace_period_max_diff = 100# making a revision- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + SiteSetting.editing_grace_period + 1.seconds,)# "roll back"- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "Hello world" },revised_at: post.updated_at + SiteSetting.editing_grace_period + 2.seconds,@@ -507,7 +513,7 @@ RSpec.describe PostRevisor doit "should bump the topic" doexpect {- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + SiteSetting.editing_grace_period + 1.seconds,@@ -520,7 +526,7 @@ RSpec.describe PostRevisor dopost_from_topic_with_no_category = Fabricate(:post, topic: topic_with_no_category)expect {result =- subject.revise!(+ post_revisor.revise!(Fabricate(:admin),raw: post_from_topic_with_no_category.raw,tags: ["foo"],@@ -533,7 +539,7 @@ RSpec.describe PostRevisor doTopicUser.create!(topic: post.topic, user: post.user, notification_level: 0)messages =MessageBus.track_publish("/latest") do- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "updated body" },revised_at: post.updated_at + SiteSetting.editing_grace_period + 1.seconds,@@ -632,12 +638,12 @@ RSpec.describe PostRevisor dobefore doSiteSetting.editing_grace_period = 1.minute- subject.revise!(post.user, { raw: "updated body" }, revised_at: revised_at)+ post_revisor.revise!(post.user, { raw: "updated body" }, revised_at: revised_at)post.reloadendit "doesn't update a category" do- expect(subject.category_changed).to be_blank+ expect(post_revisor.category_changed).to be_blankendit "updates the versions" do@@ -655,7 +661,11 @@ RSpec.describe PostRevisor dodescribe "new edit window" dobefore do- subject.revise!(post.user, { raw: "yet another updated body" }, revised_at: revised_at)+ post_revisor.revise!(+ post.user,+ { raw: "yet another updated body" },+ revised_at: revised_at,+ )post.reloadend@@ -669,14 +679,14 @@ RSpec.describe PostRevisor doendit "doesn't update a category" do- expect(subject.category_changed).to be_blank+ expect(post_revisor.category_changed).to be_blankendcontext "after second window" dolet!(:new_revised_at) { revised_at + 2.minutes }before do- subject.revise!(+ post_revisor.revise!(post.user,{ raw: "yet another, another updated body" },revised_at: new_revised_at,@@ -711,12 +721,12 @@ RSpec.describe PostRevisor docontext "with one paragraph description" dobefore do- subject.revise!(post.user, raw: new_description)+ post_revisor.revise!(post.user, raw: new_description)category.reloadendit "returns the changed category info" do- expect(subject.category_changed).to eq(category)+ expect(post_revisor.category_changed).to eq(category)endit "updates the description of the category" do@@ -726,12 +736,12 @@ RSpec.describe PostRevisor docontext "with multiple paragraph description" dobefore do- subject.revise!(post.user, raw: "#{new_description}\n\nOther content goes here.")+ post_revisor.revise!(post.user, raw: "#{new_description}\n\nOther content goes here.")category.reloadendit "returns the changed category info" do- expect(subject.category_changed).to eq(category)+ expect(post_revisor.category_changed).to eq(category)endit "updates the description of the category" do@@ -741,7 +751,7 @@ RSpec.describe PostRevisor docontext "with invalid description without paragraphs" dobefore do- subject.revise!(post.user, raw: "# This is a title")+ post_revisor.revise!(post.user, raw: "# This is a title")category.reloadend@@ -760,7 +770,7 @@ RSpec.describe PostRevisor docontext "when updating back to the original paragraph" dobefore docategory.update_column(:description, "this is my description")- subject.revise!(post.user, raw: Category.post_template)+ post_revisor.revise!(post.user, raw: Category.post_template)category.reloadend@@ -769,7 +779,7 @@ RSpec.describe PostRevisor doendit "returns the changed category info" do- expect(subject.category_changed).to eq(category)+ expect(post_revisor.category_changed).to eq(category)endendend@@ -786,16 +796,16 @@ RSpec.describe PostRevisor doit "triggers a rate limiter" doEditRateLimiter.any_instance.expects(:performed!)- subject.revise!(changed_by, raw: "updated body")+ post_revisor.revise!(changed_by, raw: "updated body")endit "raises error when a user gets rate limited" doSiteSetting.max_edits_per_day = 1user = Fabricate(:user, trust_level: 1)- subject.revise!(user, raw: "body (edited)")+ post_revisor.revise!(user, raw: "body (edited)")- expect do subject.revise!(user, raw: "body (edited twice) ") end.to raise_error(+ expect do post_revisor.revise!(user, raw: "body (edited twice) ") end.to raise_error(RateLimiter::LimitExceeded,)end@@ -807,26 +817,26 @@ RSpec.describe PostRevisor doSiteSetting.tl4_additional_edits_per_day_multiplier = 4user = Fabricate(:user, trust_level: 2)- expect { subject.revise!(user, raw: "body (edited)") }.to_not raise_error- expect { subject.revise!(user, raw: "body (edited twice)") }.to_not raise_error- expect do subject.revise!(user, raw: "body (edited three times) ") end.to raise_error(+ expect { post_revisor.revise!(user, raw: "body (edited)") }.to_not raise_error+ expect { post_revisor.revise!(user, raw: "body (edited twice)") }.to_not raise_error+ expect do post_revisor.revise!(user, raw: "body (edited three times) ") end.to raise_error(RateLimiter::LimitExceeded,)user = Fabricate(:user, trust_level: 3)- expect { subject.revise!(user, raw: "body (edited)") }.to_not raise_error- expect { subject.revise!(user, raw: "body (edited twice)") }.to_not raise_error- expect { subject.revise!(user, raw: "body (edited three times)") }.to_not raise_error- expect do subject.revise!(user, raw: "body (edited four times) ") end.to raise_error(+ expect { post_revisor.revise!(user, raw: "body (edited)") }.to_not raise_error+ expect { post_revisor.revise!(user, raw: "body (edited twice)") }.to_not raise_error+ expect { post_revisor.revise!(user, raw: "body (edited three times)") }.to_not raise_error+ expect do post_revisor.revise!(user, raw: "body (edited four times) ") end.to raise_error(RateLimiter::LimitExceeded,)user = Fabricate(:user, trust_level: 4)- expect { subject.revise!(user, raw: "body (edited)") }.to_not raise_error- expect { subject.revise!(user, raw: "body (edited twice)") }.to_not raise_error- expect { subject.revise!(user, raw: "body (edited three times)") }.to_not raise_error- expect { subject.revise!(user, raw: "body (edited four times)") }.to_not raise_error- expect do subject.revise!(user, raw: "body (edited five times) ") end.to raise_error(+ expect { post_revisor.revise!(user, raw: "body (edited)") }.to_not raise_error+ expect { post_revisor.revise!(user, raw: "body (edited twice)") }.to_not raise_error+ expect { post_revisor.revise!(user, raw: "body (edited three times)") }.to_not raise_error+ expect { post_revisor.revise!(user, raw: "body (edited four times)") }.to_not raise_error+ expect do post_revisor.revise!(user, raw: "body (edited five times) ") end.to raise_error(RateLimiter::LimitExceeded,)end@@ -839,7 +849,7 @@ RSpec.describe PostRevisor doSiteSetting.newuser_max_embedded_media = 0url = "http://i.imgur.com/wfn7rgU.jpg"Oneboxer.stubs(:onebox).with(url, anything).returns("<img src='#{url}'>")- subject.revise!(changed_by, raw: "So, post them here!\n#{url}")+ post_revisor.revise!(changed_by, raw: "So, post them here!\n#{url}")endit "allows an admin to insert images into a new user's post" do@@ -856,7 +866,7 @@ RSpec.describe PostRevisor doSiteSetting.newuser_max_embedded_media = 0url = "http://i.imgur.com/FGg7Vzu.gif"Oneboxer.stubs(:cached_onebox).with(url, anything).returns("<img src='#{url}'>")- subject.revise!(post.user, raw: "So, post them here!\n#{url}")+ post_revisor.revise!(post.user, raw: "So, post them here!\n#{url}")endit "doesn't allow images to be inserted" do@@ -868,7 +878,7 @@ RSpec.describe PostRevisor dobefore { SiteSetting.editing_grace_period_max_diff = 1000 }fab!(:changed_by) { coding_horror }- let!(:result) { subject.revise!(changed_by, raw: "lets update the body. Здравствуйте") }+ let!(:result) { post_revisor.revise!(changed_by, raw: "lets update the body. Здравствуйте") }it "correctly updates raw" doexpect(result).to eq(true)@@ -886,7 +896,7 @@ RSpec.describe PostRevisor doendit "increases the post_edits stat count" do- expect do subject.revise!(post.user, { raw: "This is a new revision" }) end.to change {+ expect do post_revisor.revise!(post.user, { raw: "This is a new revision" }) end.to change {post.user.user_stat.post_edits_count.to_i}.by(1)end@@ -894,7 +904,7 @@ RSpec.describe PostRevisor docontext "when second poster posts again quickly" doit "is a grace period edit, because the second poster posted again quickly" doSiteSetting.editing_grace_period = 1.minute- subject.revise!(+ post_revisor.revise!(changed_by,{ raw: "yet another updated body" },revised_at: post.updated_at + 10.seconds,@@ -909,7 +919,7 @@ RSpec.describe PostRevisor docontext "when passing skip_revision as true" dobefore doSiteSetting.editing_grace_period = 1.minute- subject.revise!(+ post_revisor.revise!(changed_by,{ raw: "yet another updated body" },revised_at: post.updated_at + 10.hours,@@ -928,7 +938,7 @@ RSpec.describe PostRevisor docontext "when editing the before_edit_post event signature" doit "contains post and params" doparams = { raw: "body (edited)" }- events = DiscourseEvent.track_events { subject.revise!(user, params) }+ events = DiscourseEvent.track_events { post_revisor.revise!(user, params) }expect(events).to include(event_name: :before_edit_post, params: [post, params])endend@@ -955,7 +965,7 @@ RSpec.describe PostRevisor doendit "doesn't strip starting whitespaces" do- subject.revise!(post.user, raw: " <-- whitespaces --> ")+ post_revisor.revise!(post.user, raw: " <-- whitespaces --> ")post.reloadexpect(post.raw).to eq(" <-- whitespaces -->")end@@ -963,20 +973,24 @@ RSpec.describe PostRevisor doit "revises and tracks changes of topic titles" donew_title = "New topic title"result =- subject.revise!(post.user, { title: new_title }, revised_at: post.updated_at + 10.minutes)+ post_revisor.revise!(+ post.user,+ { title: new_title },+ revised_at: post.updated_at + 10.minutes,+ )expect(result).to eq(true)post.reloadexpect(post.topic.title).to eq(new_title)expect(post.revisions.first.modifications["title"][1]).to eq(new_title)- expect(subject.topic_title_changed?).to eq(true)- expect(subject.raw_changed?).to eq(false)+ expect(post_revisor.topic_title_changed?).to eq(true)+ expect(post_revisor.raw_changed?).to eq(false)endit "revises and tracks changes of topic archetypes" donew_archetype = Archetype.bannerresult =- subject.revise!(+ post_revisor.revise!(post.user,{ archetype: new_archetype },revised_at: post.updated_at + 10.minutes,@@ -986,21 +1000,21 @@ RSpec.describe PostRevisor dopost.reloadexpect(post.topic.archetype).to eq(new_archetype)expect(post.revisions.first.modifications["archetype"][1]).to eq(new_archetype)- expect(subject.raw_changed?).to eq(false)+ expect(post_revisor.raw_changed?).to eq(false)endit "revises and tracks changes of topic tags" do- subject.revise!(admin, tags: ["new-tag"])+ post_revisor.revise!(admin, tags: ["new-tag"])expect(post.post_revisions.last.modifications).to eq("tags" => [[], ["new-tag"]])- expect(subject.raw_changed?).to eq(false)+ expect(post_revisor.raw_changed?).to eq(false)- subject.revise!(admin, tags: %w[new-tag new-tag-2])+ post_revisor.revise!(admin, tags: %w[new-tag new-tag-2])expect(post.post_revisions.last.modifications).to eq("tags" => [[], %w[new-tag new-tag-2]])- expect(subject.raw_changed?).to eq(false)+ expect(post_revisor.raw_changed?).to eq(false)- subject.revise!(admin, tags: ["new-tag-3"])+ post_revisor.revise!(admin, tags: ["new-tag-3"])expect(post.post_revisions.last.modifications).to eq("tags" => [[], ["new-tag-3"]])- expect(subject.raw_changed?).to eq(false)+ expect(post_revisor.raw_changed?).to eq(false)enddescribe "#publish_changes" do@@ -1023,14 +1037,14 @@ RSpec.describe PostRevisor docontext "when logging staff edits" doit "doesn't log when a regular user revises a post" do- subject.revise!(post.user, raw: "lets totally update the body")+ post_revisor.revise!(post.user, raw: "lets totally update the body")log =UserHistory.where(acting_user_id: post.user.id, action: UserHistory.actions[:post_edit])expect(log).to be_blankendit "logs an edit when a staff member revises a post" do- subject.revise!(moderator, raw: "lets totally update the body")+ post_revisor.revise!(moderator, raw: "lets totally update the body")log =UserHistory.where(acting_user_id: moderator.id,@@ -1041,7 +1055,11 @@ RSpec.describe PostRevisor doendit "doesn't log an edit when skip_staff_log is true" do- subject.revise!(moderator, { raw: "lets totally update the body" }, skip_staff_log: true)+ post_revisor.revise!(+ moderator,+ { raw: "lets totally update the body" },+ skip_staff_log: true,+ )log =UserHistory.where(acting_user_id: moderator.id,@@ -1095,7 +1113,7 @@ RSpec.describe PostRevisor dobefore { SiteSetting.staff_edit_locks_post = false }it "does not lock the post when revised" do- result = subject.revise!(moderator, raw: "lets totally update the body")+ result = post_revisor.revise!(moderator, raw: "lets totally update the body")expect(result).to eq(true)post.reloadexpect(post).not_to be_locked@@ -1106,7 +1124,7 @@ RSpec.describe PostRevisor dobefore { SiteSetting.staff_edit_locks_post = true }it "locks the post when revised by staff" do- result = subject.revise!(moderator, raw: "lets totally update the body")+ result = post_revisor.revise!(moderator, raw: "lets totally update the body")expect(result).to eq(true)post.reloadexpect(post).to be_locked@@ -1114,14 +1132,14 @@ RSpec.describe PostRevisor doit "doesn't lock the wiki posts" dopost.wiki = true- result = subject.revise!(moderator, raw: "some new raw content")+ result = post_revisor.revise!(moderator, raw: "some new raw content")expect(result).to eq(true)post.reloadexpect(post).not_to be_lockedendit "doesn't lock the post when the raw did not change" do- result = subject.revise!(moderator, title: "New topic title, cool!")+ result = post_revisor.revise!(moderator, title: "New topic title, cool!")expect(result).to eq(true)post.reloadexpect(post.topic.title).to eq("New topic title, cool!")@@ -1129,14 +1147,15 @@ RSpec.describe PostRevisor doendit "doesn't lock the post when revised by a regular user" do- result = subject.revise!(user, raw: "lets totally update the body")+ result = post_revisor.revise!(user, raw: "lets totally update the body")expect(result).to eq(true)post.reloadexpect(post).not_to be_lockedendit "doesn't lock the post when revised by system user" do- result = subject.revise!(Discourse.system_user, raw: "I usually replace hotlinked images")+ result =+ post_revisor.revise!(Discourse.system_user, raw: "I usually replace hotlinked images")expect(result).to eq(true)post.reloadexpect(post).not_to be_locked@@ -1161,13 +1180,16 @@ RSpec.describe PostRevisor doit "generates a notification for a mention" doexpect {- subject.revise!(user, raw: "Random user is mentioning @#{mentioned_user.username_lower}")+ post_revisor.revise!(+ user,+ raw: "Random user is mentioning @#{mentioned_user.username_lower}",+ )}.to change { Notification.where(notification_type: Notification.types[:mentioned]).count }endit "never generates a notification for a mention when the System user revise a post" doexpect {- subject.revise!(+ post_revisor.revise!(Discourse.system_user,raw: "System user is mentioning @#{mentioned_user.username_lower}",)@@ -1183,7 +1205,11 @@ RSpec.describe PostRevisor doit "doesn't add the tags" doresult =- subject.revise!(user, raw: "lets totally update the body", tags: %w[totally update])+ post_revisor.revise!(+ user,+ raw: "lets totally update the body",+ tags: %w[totally update],+ )expect(result).to eq(true)post.reloadexpect(post.topic.tags.size).to eq(0)@@ -1202,7 +1228,11 @@ RSpec.describe PostRevisor doit "can create all tags if none exist" doexpect {@result =- subject.revise!(user, raw: "lets totally update the body", tags: %w[totally update])+ post_revisor.revise!(+ user,+ raw: "lets totally update the body",+ tags: %w[totally update],+ )}.to change { Tag.count }.by(2)expect(@result).to eq(true)post.reload@@ -1213,7 +1243,11 @@ RSpec.describe PostRevisor doFabricate(:tag, name: "totally")expect {@result =- subject.revise!(user, raw: "lets totally update the body", tags: %w[totally update])+ post_revisor.revise!(+ user,+ raw: "lets totally update the body",+ tags: %w[totally update],+ )}.to change { Tag.count }.by(1)expect(@result).to eq(true)post.reload@@ -1222,7 +1256,7 @@ RSpec.describe PostRevisor doit "can remove all tags" dotopic.tags = [Fabricate(:tag, name: "super"), Fabricate(:tag, name: "stuff")]- result = subject.revise!(user, raw: "lets totally update the body", tags: [])+ result = post_revisor.revise!(user, raw: "lets totally update the body", tags: [])expect(result).to eq(true)post.reloadexpect(post.topic.tags.size).to eq(0)@@ -1231,7 +1265,11 @@ RSpec.describe PostRevisor doit "can't add staff-only tags" docreate_staff_only_tags(["important"])result =- subject.revise!(user, raw: "lets totally update the body", tags: %w[important stuff])+ post_revisor.revise!(+ user,+ raw: "lets totally update the body",+ tags: %w[important stuff],+ )expect(result).to eq(false)expect(post.topic.errors.present?).to eq(true)end@@ -1239,7 +1277,11 @@ RSpec.describe PostRevisor doit "staff can add staff-only tags" docreate_staff_only_tags(["important"])result =- subject.revise!(admin, raw: "lets totally update the body", tags: %w[important stuff])+ post_revisor.revise!(+ admin,+ raw: "lets totally update the body",+ tags: %w[important stuff],+ )expect(result).to eq(true)post.reloadexpect(post.topic.tags.map(&:name).sort).to eq(%w[important stuff])@@ -1250,7 +1292,7 @@ RSpec.describe PostRevisor doevents =DiscourseEvent.track_events do- subject.revise!(user, raw: "lets totally update the body", tags: [])+ post_revisor.revise!(user, raw: "lets totally update the body", tags: [])endevent = events.find { |e| e[:event_name] == :post_edited }@@ -1273,7 +1315,8 @@ RSpec.describe PostRevisor doendit "staff-only tags can't be removed" do- result = subject.revise!(user, raw: "lets totally update the body", tags: ["stuff"])+ result =+ post_revisor.revise!(user, raw: "lets totally update the body", tags: ["stuff"])expect(result).to eq(false)expect(post.topic.errors.present?).to eq(true)post.reload@@ -1281,7 +1324,7 @@ RSpec.describe PostRevisor doendit "can't remove all tags if some are staff-only" do- result = subject.revise!(user, raw: "lets totally update the body", tags: [])+ result = post_revisor.revise!(user, raw: "lets totally update the body", tags: [])expect(result).to eq(false)expect(post.topic.errors.present?).to eq(true)post.reload@@ -1289,14 +1332,15 @@ RSpec.describe PostRevisor doendit "staff-only tags can be removed by staff" do- result = subject.revise!(admin, raw: "lets totally update the body", tags: ["stuff"])+ result =+ post_revisor.revise!(admin, raw: "lets totally update the body", tags: ["stuff"])expect(result).to eq(true)post.reloadexpect(post.topic.tags.map(&:name)).to eq(["stuff"])endit "staff can remove all tags" do- result = subject.revise!(admin, raw: "lets totally update the body", tags: [])+ result = post_revisor.revise!(admin, raw: "lets totally update the body", tags: [])expect(result).to eq(true)post.reloadexpect(post.topic.tags.size).to eq(0)@@ -1320,7 +1364,7 @@ RSpec.describe PostRevisor doit "doesn't bump topic if only staff-only tags are added" doexpect {result =- subject.revise!(+ post_revisor.revise!(Fabricate(:admin),raw: post.raw,tags: topic.tags.map(&:name) + ["secret"],@@ -1332,7 +1376,7 @@ RSpec.describe PostRevisor doit "doesn't bump topic if only staff-only tags are removed" doexpect {result =- subject.revise!(+ post_revisor.revise!(Fabricate(:admin),raw: post.raw,tags: topic.tags.map(&:name) - %w[important secret],@@ -1344,7 +1388,7 @@ RSpec.describe PostRevisor doit "doesn't bump topic if only staff-only tags are removed and there are no tags left" dotopic.tags = Tag.where(name: %w[important secret]).to_aexpect {- result = subject.revise!(Fabricate(:admin), raw: post.raw, tags: [])+ result = post_revisor.revise!(Fabricate(:admin), raw: post.raw, tags: [])expect(result).to eq(true)}.to_not change { topic.reload.bumped_at }end@@ -1352,7 +1396,7 @@ RSpec.describe PostRevisor doit "doesn't bump topic if empty string is given" dotopic.tags = Tag.where(name: %w[important secret]).to_aexpect {- result = subject.revise!(Fabricate(:admin), raw: post.raw, tags: [""])+ result = post_revisor.revise!(Fabricate(:admin), raw: post.raw, tags: [""])expect(result).to eq(true)}.to_not change { topic.reload.bumped_at }end@@ -1360,7 +1404,7 @@ RSpec.describe PostRevisor doit "should bump topic if non staff-only tags are added" doexpect {result =- subject.revise!(+ post_revisor.revise!(Fabricate(:admin),raw: post.raw,tags: topic.tags.map(&:name) + [Fabricate(:tag).name],@@ -1370,7 +1414,7 @@ RSpec.describe PostRevisor doendit "creates a hidden revision" do- subject.revise!(+ post_revisor.revise!(Fabricate(:admin),raw: post.raw,tags: topic.tags.map(&:name) + ["secret"],@@ -1382,7 +1426,7 @@ RSpec.describe PostRevisor doPostActionNotifier.enableJobs.run_immediately!expect {- subject.revise!(+ post_revisor.revise!(Fabricate(:admin),raw: post.raw,tags: topic.tags.map(&:name) + ["secret"],@@ -1412,20 +1456,21 @@ RSpec.describe PostRevisor doit "doesn't allow removing all tags from the group" dopost.topic.tags = [tag1, tag2]- result = subject.revise!(user, raw: "lets totally update the body", tags: [])+ result = post_revisor.revise!(user, raw: "lets totally update the body", tags: [])expect(result).to eq(false)endit "allows removing some tags" dopost.topic.tags = [tag1, tag2, tag3]- result = subject.revise!(user, raw: "lets totally update the body", tags: [tag1.name])+ result =+ post_revisor.revise!(user, raw: "lets totally update the body", tags: [tag1.name])expect(result).to eq(true)expect(post.reload.topic.tags.map(&:name)).to eq([tag1.name])endit "allows admins to remove the tags" dopost.topic.tags = [tag1, tag2, tag3]- result = subject.revise!(admin, raw: "lets totally update the body", tags: [])+ result = post_revisor.revise!(admin, raw: "lets totally update the body", tags: [])expect(result).to eq(true)expect(post.reload.topic.tags.size).to eq(0)end@@ -1442,7 +1487,11 @@ RSpec.describe PostRevisor doFabricate(:tag, name: "totally")expect {@result =- subject.revise!(user, raw: "lets totally update the body", tags: %w[totally update])+ post_revisor.revise!(+ user,+ raw: "lets totally update the body",+ tags: %w[totally update],+ )}.to_not change { Tag.count }expect(@result).to eq(true)post.reload@@ -1467,7 +1516,7 @@ RSpec.describe PostRevisor dopost.link_post_uploadsexpect(post.upload_references.pluck(:upload_id)).to contain_exactly(image1.id, image2.id)- subject.revise!(user, raw: <<~RAW)+ post_revisor.revise!(user, raw: <<~RAW)This is a post with multiple uploads@@ -1493,7 +1542,7 @@ RSpec.describe PostRevisor doit "updates the upload secure status, which is secure by default from the composer. set to false for a public topic" dostub_image_size- subject.revise!(user, raw: <<~RAW)+ post_revisor.revise!(user, raw: <<~RAW)This is a post with a secure uploadRAW@@ -1507,7 +1556,7 @@ RSpec.describe PostRevisor doit "does not update the upload secure status, which is secure by default from the composer for a private" dopost.topic.update(category: Fabricate(:private_category, group: Fabricate(:group)))stub_image_size- subject.revise!(user, raw: <<~RAW)+ post_revisor.revise!(user, raw: <<~RAW)This is a post with a secure uploadRAW@@ -1554,12 +1603,12 @@ RSpec.describe PostRevisor dofab!(:post) { Fabricate(:post, raw: "aaa", skip_validation: true) }it "can revise multiple times and remove unnecessary revisions" do- subject.revise!(admin, { raw: "bbb" }, skip_validations: true)+ post_revisor.revise!(admin, { raw: "bbb" }, skip_validations: true)expect(post.errors).to be_empty# Revert to old version which was invalid to destroy previously created# post revision and trigger another post save.- subject.revise!(admin, { raw: "aaa" }, skip_validations: true)+ post_revisor.revise!(admin, { raw: "aaa" }, skip_validations: true)expect(post.errors).to be_emptyendenddiff --git a/spec/lib/retrieve_title_spec.rb b/spec/lib/retrieve_title_spec.rbindex 5afc01a0d7a..685696efb50 100644--- a/spec/lib/retrieve_title_spec.rb+++ b/spec/lib/retrieve_title_spec.rb@@ -203,7 +203,7 @@ RSpec.describe RetrieveTitle doendit "ignores SSRF lookup errors" do- subject.stubs(:fetch_title).raises(FinalDestination::SSRFDetector::LookupFailedError)+ described_class.stubs(:fetch_title).raises(FinalDestination::SSRFDetector::LookupFailedError)expect(RetrieveTitle.crawl("https://example.com")).to eq(nil)enddiff --git a/spec/lib/seed_data/categories_spec.rb b/spec/lib/seed_data/categories_spec.rbindex a9fccb9605c..fa92fbe12a3 100644--- a/spec/lib/seed_data/categories_spec.rb+++ b/spec/lib/seed_data/categories_spec.rb@@ -3,10 +3,10 @@require "seed_data/categories"RSpec.describe SeedData::Categories do- subject { SeedData::Categories.with_default_locale }+ subject(:seeder) { SeedData::Categories.with_default_locale }def create_category(name = "staff_category_id")- subject.create(site_setting_names: [name])+ seeder.create(site_setting_names: [name])enddef description_post(category)@@ -152,7 +152,7 @@ RSpec.describe SeedData::Categories dodescribe "#update" dodef update_category(name = "staff_category_id", skip_changed: false)- subject.update(site_setting_names: [name], skip_changed: skip_changed)+ seeder.update(site_setting_names: [name], skip_changed: skip_changed)endbefore do@@ -211,7 +211,7 @@ RSpec.describe SeedData::Categories do{ id: "general_category_id", name: I18n.t("general_category_name"), selected: false },]- expect(subject.reseed_options).to eq(expected_options)+ expect(seeder.reseed_options).to eq(expected_options)endendenddiff --git a/spec/lib/seed_data/topics_spec.rb b/spec/lib/seed_data/topics_spec.rbindex 67361eb5c5f..afea102617b 100644--- a/spec/lib/seed_data/topics_spec.rb+++ b/spec/lib/seed_data/topics_spec.rb@@ -3,7 +3,7 @@require "seed_data/topics"RSpec.describe SeedData::Topics do- subject { SeedData::Topics.with_default_locale }+ subject(:seeder) { SeedData::Topics.with_default_locale }before dogeneral_category = Fabricate(:category, name: "General")@@ -11,7 +11,7 @@ RSpec.describe SeedData::Topics doenddef create_topic(name = "welcome_topic_id")- subject.create(site_setting_names: [name], include_legal_topics: true)+ seeder.create(site_setting_names: [name], include_legal_topics: true)enddescribe "#create" do@@ -74,7 +74,7 @@ RSpec.describe SeedData::Topics doendit "does not create a legal topic if company_name is not set" do- subject.create(site_setting_names: ["tos_topic_id"])+ seeder.create(site_setting_names: ["tos_topic_id"])expect(SiteSetting.tos_topic_id).to eq(-1)end@@ -102,7 +102,7 @@ RSpec.describe SeedData::Topics doit "creates a legal topic if company_name is set" doSiteSetting.company_name = "Company Name"- subject.create(site_setting_names: ["tos_topic_id"])+ seeder.create(site_setting_names: ["tos_topic_id"])expect(SiteSetting.tos_topic_id).to_not eq(-1)end@@ -110,7 +110,7 @@ RSpec.describe SeedData::Topics dodescribe "#update" dodef update_topic(name = "welcome_topic_id", skip_changed: false)- subject.update(site_setting_names: [name], skip_changed: skip_changed)+ seeder.update(site_setting_names: [name], skip_changed: skip_changed)endit "updates the changed topic" do@@ -167,7 +167,7 @@ RSpec.describe SeedData::Topics dodescribe "#delete" dodef delete_topic(name = "welcome_topic_id", skip_changed: false)- subject.delete(site_setting_names: [name], skip_changed: skip_changed)+ seeder.delete(site_setting_names: [name], skip_changed: skip_changed)endit "deletes the topic" do@@ -199,7 +199,7 @@ RSpec.describe SeedData::Topics do{ id: "welcome_topic_id", name: "Changed Topic Title", selected: false },]- expect(subject.reseed_options).to eq(expected_options)+ expect(seeder.reseed_options).to eq(expected_options)endendenddiff --git a/spec/lib/site_settings/type_supervisor_spec.rb b/spec/lib/site_settings/type_supervisor_spec.rbindex 45bd084d93f..b1d416c18d6 100644--- a/spec/lib/site_settings/type_supervisor_spec.rb+++ b/spec/lib/site_settings/type_supervisor_spec.rb@@ -9,8 +9,6 @@ RSpec.describe SiteSettings::TypeSupervisor donew_settings(provider_local)end- subject { SiteSettings::TypeSupervisor }-describe "constants" doit "validator opts are the subset of consumed opts" doexpect(@@ -103,33 +101,33 @@ RSpec.describe SiteSettings::TypeSupervisor dodescribe "#parse_value_type" doit "returns :null type when the value is nil" do- expect(subject.parse_value_type(nil)).to eq(SiteSetting.types[:null])+ expect(described_class.parse_value_type(nil)).to eq(SiteSetting.types[:null])endit "returns :integer type when the value is int" do- expect(subject.parse_value_type(2)).to eq(SiteSetting.types[:integer])+ expect(described_class.parse_value_type(2)).to eq(SiteSetting.types[:integer])endit "returns :integer type when the value is large int" do- expect(subject.parse_value_type(99_999_999_999_999_999_999_999_999_999_999_999)).to eq(- SiteSetting.types[:integer],- )+ expect(+ described_class.parse_value_type(99_999_999_999_999_999_999_999_999_999_999_999),+ ).to eq(SiteSetting.types[:integer])endit "returns :float type when the value is float" do- expect(subject.parse_value_type(1.23)).to eq(SiteSetting.types[:float])+ expect(described_class.parse_value_type(1.23)).to eq(SiteSetting.types[:float])endit "returns :bool type when the value is true" do- expect(subject.parse_value_type(true)).to eq(SiteSetting.types[:bool])+ expect(described_class.parse_value_type(true)).to eq(SiteSetting.types[:bool])endit "returns :bool type when the value is false" do- expect(subject.parse_value_type(false)).to eq(SiteSetting.types[:bool])+ expect(described_class.parse_value_type(false)).to eq(SiteSetting.types[:bool])endit "raises when the value is not listed" do- expect { subject.parse_value_type(Object.new) }.to raise_error ArgumentError+ expect { described_class.parse_value_type(Object.new) }.to raise_error ArgumentErrorendenddiff --git a/spec/lib/site_settings/validations_spec.rb b/spec/lib/site_settings/validations_spec.rbindex 82064f35932..2b6e392c547 100644--- a/spec/lib/site_settings/validations_spec.rb+++ b/spec/lib/site_settings/validations_spec.rb@@ -3,22 +3,24 @@require "site_settings/validations"RSpec.describe SiteSettings::Validations do- subject { Class.new.include(described_class).new }+ subject(:validations) { Class.new.include(described_class).new }describe "default_categories" dofab!(:category) { Fabricate(:category) }it "supports valid categories" do- expect { subject.validate_default_categories_watching("#{category.id}") }.not_to raise_error+ expect {+ validations.validate_default_categories_watching("#{category.id}")+ }.not_to raise_errorendit "won't allow you to input junk categories" do- expect { subject.validate_default_categories_watching("junk") }.to raise_error(+ expect { validations.validate_default_categories_watching("junk") }.to raise_error(Discourse::InvalidParameters,)expect {- subject.validate_default_categories_watching("#{category.id}|12312323")+ validations.validate_default_categories_watching("#{category.id}|12312323")}.to raise_error(Discourse::InvalidParameters)end@@ -85,7 +87,7 @@ RSpec.describe SiteSettings::Validations dolet(:other_setting_name) { "s3_upload_bucket" }def validate(new_value)- subject.validate_s3_backup_bucket(new_value)+ validations.validate_s3_backup_bucket(new_value)endit_behaves_like "s3 bucket validation"@@ -103,7 +105,7 @@ RSpec.describe SiteSettings::Validations dolet(:other_setting_name) { "s3_backup_bucket" }def validate(new_value)- subject.validate_s3_upload_bucket(new_value)+ validations.validate_s3_upload_bucket(new_value)endit_behaves_like "s3 bucket validation"@@ -142,7 +144,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.enable_local_logins = false }it "should raise an error" do- expect { subject.validate_enforce_second_factor("t") }.to raise_error(+ expect { validations.validate_enforce_second_factor("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -153,7 +155,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.enable_local_logins = true }it "should be ok" do- expect { subject.validate_enforce_second_factor("t") }.not_to raise_error+ expect { validations.validate_enforce_second_factor("t") }.not_to raise_errorendend@@ -170,7 +172,7 @@ RSpec.describe SiteSettings::Validations doendit "raises and error, and specifies the auth providers" do- expect { subject.validate_enforce_second_factor("all") }.to raise_error(+ expect { validations.validate_enforce_second_factor("all") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -189,7 +191,7 @@ RSpec.describe SiteSettings::Validations doendit "should raise an error" do- expect { subject.validate_enforce_second_factor("t") }.to raise_error(+ expect { validations.validate_enforce_second_factor("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -207,7 +209,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.enforce_second_factor = "all" }it "should raise an error" do- expect { subject.validate_enable_local_logins("f") }.to raise_error(+ expect { validations.validate_enable_local_logins("f") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -218,14 +220,14 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.enforce_second_factor = "no" }it "should be ok" do- expect { subject.validate_enable_local_logins("f") }.not_to raise_error+ expect { validations.validate_enable_local_logins("f") }.not_to raise_errorendendendcontext "when the new value is true" doit "should be ok" do- expect { subject.validate_enable_local_logins("t") }.not_to raise_error+ expect { validations.validate_enable_local_logins("t") }.not_to raise_errorendendend@@ -237,7 +239,7 @@ RSpec.describe SiteSettings::Validations docontext "when the new value has trailing slash" doit "should raise an error" do- expect { subject.validate_cors_origins("https://www.rainbows.com/") }.to raise_error(+ expect { validations.validate_cors_origins("https://www.rainbows.com/") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -248,7 +250,7 @@ RSpec.describe SiteSettings::Validations dodescribe "#validate_enable_page_publishing" docontext "when the new value is true" doit "is ok" do- expect { subject.validate_enable_page_publishing("t") }.not_to raise_error+ expect { validations.validate_enable_page_publishing("t") }.not_to raise_errorendcontext "if secure uploads is enabled" do@@ -256,7 +258,7 @@ RSpec.describe SiteSettings::Validations dobefore { enable_secure_uploads }it "is not ok" do- expect { subject.validate_enable_page_publishing("t") }.to raise_error(+ expect { validations.validate_enable_page_publishing("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -268,13 +270,13 @@ RSpec.describe SiteSettings::Validations dodescribe "#validate_s3_use_acls" docontext "when the new value is true" doit "is ok" do- expect { subject.validate_s3_use_acls("t") }.not_to raise_error+ expect { validations.validate_s3_use_acls("t") }.not_to raise_errorendendcontext "when the new value is false" doit "is ok" do- expect { subject.validate_s3_use_acls("f") }.not_to raise_error+ expect { validations.validate_s3_use_acls("f") }.not_to raise_errorendcontext "if secure uploads is enabled" do@@ -282,7 +284,7 @@ RSpec.describe SiteSettings::Validations dobefore { enable_secure_uploads }it "is not ok" do- expect { subject.validate_s3_use_acls("f") }.to raise_error(+ expect { validations.validate_s3_use_acls("f") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -299,7 +301,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.enable_s3_uploads = true }it "should be ok" do- expect { subject.validate_secure_uploads("t") }.not_to raise_error+ expect { validations.validate_secure_uploads("t") }.not_to raise_errorendend@@ -307,7 +309,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.enable_s3_uploads = false }it "is not ok" do- expect { subject.validate_secure_uploads("t") }.to raise_error(+ expect { validations.validate_secure_uploads("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -317,7 +319,7 @@ RSpec.describe SiteSettings::Validations dobefore { GlobalSetting.stubs(:use_s3?).returns(true) }it "should be ok" do- expect { subject.validate_secure_uploads("t") }.not_to raise_error+ expect { validations.validate_secure_uploads("t") }.not_to raise_errorendendend@@ -326,7 +328,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.s3_use_acls = false }it "is not ok" do- expect { subject.validate_secure_uploads("t") }.to raise_error(+ expect { validations.validate_secure_uploads("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -345,7 +347,7 @@ RSpec.describe SiteSettings::Validations dobefore { GlobalSetting.stubs(:use_s3?).returns(true) }it "is not ok" do- expect { subject.validate_enable_s3_uploads("t") }.to raise_error(+ expect { validations.validate_enable_s3_uploads("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -356,7 +358,7 @@ RSpec.describe SiteSettings::Validations dobefore { GlobalSetting.stubs(:use_s3?).returns(false) }it "should be ok" do- expect { subject.validate_enable_s3_uploads("t") }.not_to raise_error+ expect { validations.validate_enable_s3_uploads("t") }.not_to raise_errorendend@@ -366,7 +368,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.s3_upload_bucket = nil }it "is not ok" do- expect { subject.validate_enable_s3_uploads("t") }.to raise_error(+ expect { validations.validate_enable_s3_uploads("t") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -377,7 +379,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.s3_upload_bucket = "some-bucket" }it "should be ok" do- expect { subject.validate_enable_s3_uploads("t") }.not_to raise_error+ expect { validations.validate_enable_s3_uploads("t") }.not_to raise_errorendendend@@ -399,49 +401,47 @@ RSpec.describe SiteSettings::Validations doendit "cannot contain a user agent that's shorter than 3 characters" do- expect { subject.validate_slow_down_crawler_user_agents("ao|acsw") }.to raise_error(+ expect { validations.validate_slow_down_crawler_user_agents("ao|acsw") }.to raise_error(Discourse::InvalidParameters,too_short_message,)- expect { subject.validate_slow_down_crawler_user_agents("up") }.to raise_error(+ expect { validations.validate_slow_down_crawler_user_agents("up") }.to raise_error(Discourse::InvalidParameters,too_short_message,)- expect { subject.validate_slow_down_crawler_user_agents("a|") }.to raise_error(+ expect { validations.validate_slow_down_crawler_user_agents("a|") }.to raise_error(Discourse::InvalidParameters,too_short_message,)- expect { subject.validate_slow_down_crawler_user_agents("|a") }.to raise_error(+ expect { validations.validate_slow_down_crawler_user_agents("|a") }.to raise_error(Discourse::InvalidParameters,too_short_message,)endit "allows user agents that are 3 characters or longer" do- expect { subject.validate_slow_down_crawler_user_agents("aoc") }.not_to raise_error- expect { subject.validate_slow_down_crawler_user_agents("anuq") }.not_to raise_error- expect { subject.validate_slow_down_crawler_user_agents("pupsc|kcx") }.not_to raise_error+ expect { validations.validate_slow_down_crawler_user_agents("aoc") }.not_to raise_error+ expect { validations.validate_slow_down_crawler_user_agents("anuq") }.not_to raise_error+ expect { validations.validate_slow_down_crawler_user_agents("pupsc|kcx") }.not_to raise_errorendit "allows the setting to be empty" do- expect { subject.validate_slow_down_crawler_user_agents("") }.not_to raise_error+ expect { validations.validate_slow_down_crawler_user_agents("") }.not_to raise_errorendit "cannot contain a token of a popular browser user agent" do- expect { subject.validate_slow_down_crawler_user_agents("mOzilla") }.to raise_error(+ expect { validations.validate_slow_down_crawler_user_agents("mOzilla") }.to raise_error(Discourse::InvalidParameters,popular_browser_message,)- expect { subject.validate_slow_down_crawler_user_agents("chRome|badcrawler") }.to raise_error(- Discourse::InvalidParameters,- popular_browser_message,- )+ expect {+ validations.validate_slow_down_crawler_user_agents("chRome|badcrawler")+ }.to raise_error(Discourse::InvalidParameters, popular_browser_message)- expect { subject.validate_slow_down_crawler_user_agents("html|badcrawler") }.to raise_error(- Discourse::InvalidParameters,- popular_browser_message,- )+ expect {+ validations.validate_slow_down_crawler_user_agents("html|badcrawler")+ }.to raise_error(Discourse::InvalidParameters, popular_browser_message)endend@@ -458,7 +458,7 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.composer_media_optimization_image_enabled = true }it "should raise an error" do- expect { subject.validate_strip_image_metadata("f") }.to raise_error(+ expect { validations.validate_strip_image_metadata("f") }.to raise_error(Discourse::InvalidParameters,error_message,)@@ -469,14 +469,14 @@ RSpec.describe SiteSettings::Validations dobefore { SiteSetting.composer_media_optimization_image_enabled = false }it "should be ok" do- expect { subject.validate_strip_image_metadata("f") }.not_to raise_error+ expect { validations.validate_strip_image_metadata("f") }.not_to raise_errorendendendcontext "when the new value is true" doit "should be ok" do- expect { subject.validate_strip_image_metadata("t") }.not_to raise_error+ expect { validations.validate_strip_image_metadata("t") }.not_to raise_errorendendend@@ -485,13 +485,13 @@ RSpec.describe SiteSettings::Validations dodescribe "#twitter_summary_large_image" doit "does not allow SVG image files" doupload = Fabricate(:upload, url: "/images/logo-dark.svg", extension: "svg")- expect { subject.validate_twitter_summary_large_image(upload.id) }.to raise_error(+ expect { validations.validate_twitter_summary_large_image(upload.id) }.to raise_error(Discourse::InvalidParameters,I18n.t("errors.site_settings.twitter_summary_large_image_no_svg"),)upload.update!(url: "/images/logo-dark.png", extension: "png")- expect { subject.validate_twitter_summary_large_image(upload.id) }.not_to raise_error- expect { subject.validate_twitter_summary_large_image(nil) }.not_to raise_error+ expect { validations.validate_twitter_summary_large_image(upload.id) }.not_to raise_error+ expect { validations.validate_twitter_summary_large_image(nil) }.not_to raise_errorendendenddiff --git a/spec/lib/topic_upload_security_manager_spec.rb b/spec/lib/topic_upload_security_manager_spec.rbindex 41c4db69a2a..c684444312f 100644--- a/spec/lib/topic_upload_security_manager_spec.rb+++ b/spec/lib/topic_upload_security_manager_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe TopicUploadSecurityManager do+ subject(:manager) { described_class.new(topic) }+let(:group) { Fabricate(:group) }let(:category) { Fabricate(:category) }let!(:topic) { Fabricate(:topic, user: user, category: category) }@@ -10,8 +12,6 @@ RSpec.describe TopicUploadSecurityManager dolet!(:post3) { Fabricate(:post, topic: topic) }let!(:post4) { Fabricate(:post, topic: topic) }- subject { described_class.new(topic) }-context "when a topic has posts linked to secure uploads" dolet!(:upload) { Fabricate(:secure_upload) }let!(:upload2) { Fabricate(:secure_upload) }@@ -127,7 +127,7 @@ RSpec.describe TopicUploadSecurityManager doit "changes the upload secure status to true and changes the ACL and rebakes the post and sets the access control post" doPost.any_instance.expects(:rebake!).once- subject.run+ manager.runexpect(upload3.reload.secure?).to eq(true)expect(upload3.reload.access_control_post).to eq(post4)end@@ -136,7 +136,7 @@ RSpec.describe TopicUploadSecurityManager dobefore { SiteSetting.secure_uploads = false }it "does not change the upload secure status and does not set the access control post" do- subject.run+ manager.runexpect(upload3.reload.secure?).to eq(false)expect(upload3.reload.access_control_post).to eq(nil)end@@ -151,7 +151,7 @@ RSpec.describe TopicUploadSecurityManager doit "does not change the upload secure status and does not set the access control post" doPost.any_instance.expects(:rebake!).never- subject.run+ manager.runexpect(upload3.reload.secure?).to eq(false)expect(upload3.reload.access_control_post).to eq(nil)end@@ -161,14 +161,14 @@ RSpec.describe TopicUploadSecurityManager dodef expect_upload_status_not_to_changePost.any_instance.expects(:rebake!).never- subject.run+ manager.runexpect(upload.reload.secure?).to eq(true)expect(upload2.reload.secure?).to eq(true)enddef expect_upload_status_to_change_and_rebakePost.any_instance.expects(:rebake!).twice- subject.run+ manager.runexpect(upload.reload.secure?).to eq(false)expect(upload2.reload.secure?).to eq(false)enddiff --git a/spec/lib/upload_security_spec.rb b/spec/lib/upload_security_spec.rbindex a4feac8646d..7ad9174a757 100644--- a/spec/lib/upload_security_spec.rb+++ b/spec/lib/upload_security_spec.rb@@ -1,16 +1,17 @@# frozen_string_literal: trueRSpec.describe UploadSecurity do+ subject(:security) { described_class.new(upload, opts) }+fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }fab!(:post_in_secure_context) doFabricate(:post, topic: Fabricate(:topic, category: private_category))endfab!(:upload) { Fabricate(:upload) }+let(:type) { nil }let(:opts) { { type: type, creating: creating } }- subject { described_class.new(upload, opts) }-context "when secure uploads is enabled" dobefore dosetup_s3@@ -24,63 +25,63 @@ RSpec.describe UploadSecurity dobefore { SiteSetting.login_required = true }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endcontext "when uploading in public context" dodescribe "for a public type badge_image" dolet(:type) { "badge_image" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type group_flair" dolet(:type) { "group_flair" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type avatar" dolet(:type) { "avatar" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type custom_emoji" dolet(:type) { "custom_emoji" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type profile_background" dolet(:type) { "profile_background" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type avatar" dolet(:type) { "avatar" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type category_logo" dolet(:type) { "category_logo" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endenddescribe "for a public type category_background" dolet(:type) { "category_background" }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -88,12 +89,12 @@ RSpec.describe UploadSecurity dolet(:type) { "my_custom_type" }it "returns true if the custom type has not been added" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endit "returns false if the custom type has been added" doUploadSecurity.register_custom_public_type(type)- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)UploadSecurity.reset_custom_public_typesendend@@ -102,7 +103,7 @@ RSpec.describe UploadSecurity dobefore { upload.stubs(:for_theme).returns(true) }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -110,7 +111,7 @@ RSpec.describe UploadSecurity dobefore { upload.stubs(:for_site_setting).returns(true) }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -118,7 +119,7 @@ RSpec.describe UploadSecurity dobefore { upload.stubs(:for_gravatar).returns(true) }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -129,7 +130,7 @@ RSpec.describe UploadSecurity doe.url == "/images/emoji/twitter/falafel.png?v=#{Emoji::EMOJI_VERSION}"endupload.update!(origin: "http://localhost:3000#{falafel.url}")- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endendend@@ -139,14 +140,14 @@ RSpec.describe UploadSecurity dobefore { upload.update(access_control_post_id: post_in_secure_context.id) }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endcontext "when the post is deleted" dobefore { post_in_secure_context.trash! }it "still determines whether the post has secure uploads; returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endendend@@ -154,28 +155,28 @@ RSpec.describe UploadSecurity docontext "when uploading in the composer" dolet(:type) { "composer" }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endendcontext "when uploading for a group message" dobefore { upload.stubs(:for_group_message).returns(true) }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endendcontext "when uploading for a PM" dobefore { upload.stubs(:for_private_message).returns(true) }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endendcontext "when upload is already secure" dobefore { upload.update(secure: true) }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endend@@ -185,7 +186,7 @@ RSpec.describe UploadSecurity docontext "when the access control post has_secure_uploads?" dobefore { upload.update(access_control_post: post_in_secure_context) }it "returns true" do- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endendend@@ -213,7 +214,7 @@ RSpec.describe UploadSecurity dodescribe "when the upload is first used for a post in a secure context" doit "returns true" docreate_secure_post_reference- expect(subject.should_be_secure?).to eq(true)+ expect(security.should_be_secure?).to eq(true)endend@@ -223,7 +224,7 @@ RSpec.describe UploadSecurity dopost_in_secure_context.trash!CustomEmoji.create(name: "meme", upload: upload)- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -231,7 +232,7 @@ RSpec.describe UploadSecurity doit "returns false" doSiteSetting.favicon = uploadcreate_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -239,7 +240,7 @@ RSpec.describe UploadSecurity doit "returns false" doFabricate(:theme_field, type_id: ThemeField.types[:theme_upload_var], upload: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -247,7 +248,7 @@ RSpec.describe UploadSecurity doit "returns false" doFabricate(:group, flair_upload: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -255,7 +256,7 @@ RSpec.describe UploadSecurity doit "returns false" doCustomEmoji.create(name: "meme", upload: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endcontext "when the created_at dates for upload references are identical" do@@ -266,7 +267,7 @@ RSpec.describe UploadSecurity doUploadReference.find_by(target: custom_emoji).update!(created_at: now)UploadReference.find_by(target: post_in_secure_context).update!(created_at: now)- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endendend@@ -275,7 +276,7 @@ RSpec.describe UploadSecurity doit "returns false" doFabricate(:badge, image_upload: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -283,7 +284,7 @@ RSpec.describe UploadSecurity doit "returns false" doFabricate(:category, uploaded_logo: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -292,7 +293,7 @@ RSpec.describe UploadSecurity douser = Fabricate(:user)user.user_profile.update!(card_background_upload: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -300,7 +301,7 @@ RSpec.describe UploadSecurity doit "returns false" doFabricate(:user, uploaded_avatar: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endend@@ -308,7 +309,7 @@ RSpec.describe UploadSecurity doit "returns false" doFabricate(:user_avatar, custom_upload: upload)create_secure_post_reference- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endendend@@ -320,14 +321,14 @@ RSpec.describe UploadSecurity dobefore { SiteSetting.secure_uploads = false }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endcontext "for attachments" dobefore { upload.update(original_filename: "test.pdf") }it "returns false" do- expect(subject.should_be_secure?).to eq(false)+ expect(security.should_be_secure?).to eq(false)endendenddiff --git a/spec/lib/user_comm_screener_spec.rb b/spec/lib/user_comm_screener_spec.rbindex 4f8b851a58a..1305c3f51e9 100644--- a/spec/lib/user_comm_screener_spec.rb+++ b/spec/lib/user_comm_screener_spec.rb@@ -1,18 +1,7 @@# frozen_string_literal: trueRSpec.describe UserCommScreener do- fab!(:target_user1) { Fabricate(:user, username: "bobscreen") }- fab!(:target_user2) { Fabricate(:user, username: "hughscreen") }- fab!(:target_user3) do- user = Fabricate(:user, username: "alicescreen")- user.user_option.update(allow_private_messages: false)- user- end- fab!(:target_user4) { Fabricate(:user, username: "janescreen") }- fab!(:target_user5) { Fabricate(:user, username: "maryscreen") }- fab!(:other_user) { Fabricate(:user) }-- subject do+ subject(:screener) dodescribed_class.new(acting_user: acting_user,target_user_ids: [@@ -25,6 +14,17 @@ RSpec.describe UserCommScreener do)end+ fab!(:target_user1) { Fabricate(:user, username: "bobscreen") }+ fab!(:target_user2) { Fabricate(:user, username: "hughscreen") }+ fab!(:target_user3) do+ user = Fabricate(:user, username: "alicescreen")+ user.user_option.update(allow_private_messages: false)+ user+ end+ fab!(:target_user4) { Fabricate(:user, username: "janescreen") }+ fab!(:target_user5) { Fabricate(:user, username: "maryscreen") }+ fab!(:other_user) { Fabricate(:user) }+it "allows initializing the class with both an acting_user_id and an acting_user" doacting_user = Fabricate(:user)screener = described_class.new(acting_user: acting_user, target_user_ids: [target_user1.id])@@ -58,7 +58,7 @@ RSpec.describe UserCommScreener dodescribe "#allowing_actor_communication" doit "returns the usernames of people not ignoring, muting, or disallowing PMs from the actor" do- expect(subject.allowing_actor_communication).to match_array(+ expect(screener.allowing_actor_communication).to match_array([target_user4.id, target_user5.id],)end@@ -66,7 +66,7 @@ RSpec.describe UserCommScreener dodescribe "#preventing_actor_communication" doit "returns the usernames of people ignoring, muting, or disallowing PMs from the actor" do- expect(subject.preventing_actor_communication).to match_array(+ expect(screener.preventing_actor_communication).to match_array([target_user1.id, target_user2.id, target_user3.id],)end@@ -74,23 +74,23 @@ RSpec.describe UserCommScreener dodescribe "#ignoring_or_muting_actor?" doit "does not raise an error when looking for a user who has no communication preferences" do- expect { subject.ignoring_or_muting_actor?(target_user5.id) }.not_to raise_error+ expect { screener.ignoring_or_muting_actor?(target_user5.id) }.not_to raise_errorendit "returns true for a user muting the actor" do- expect(subject.ignoring_or_muting_actor?(target_user1.id)).to eq(true)+ expect(screener.ignoring_or_muting_actor?(target_user1.id)).to eq(true)endit "returns true for a user ignoring the actor" do- expect(subject.ignoring_or_muting_actor?(target_user2.id)).to eq(true)+ expect(screener.ignoring_or_muting_actor?(target_user2.id)).to eq(true)endit "returns false for a user neither ignoring or muting the actor" do- expect(subject.ignoring_or_muting_actor?(target_user3.id)).to eq(false)+ expect(screener.ignoring_or_muting_actor?(target_user3.id)).to eq(false)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.ignoring_or_muting_actor?(other_user.id) }.to raise_error(+ expect { screener.ignoring_or_muting_actor?(other_user.id) }.to raise_error(Discourse::NotFound,)end@@ -98,34 +98,34 @@ RSpec.describe UserCommScreener dodescribe "#disallowing_pms_from_actor?" doit "returns true for a user disallowing all PMs" do- expect(subject.disallowing_pms_from_actor?(target_user3.id)).to eq(true)+ expect(screener.disallowing_pms_from_actor?(target_user3.id)).to eq(true)endit "returns true for a user allowing only PMs for certain users but not the actor" dotarget_user4.user_option.update!(enable_allowed_pm_users: true)- expect(subject.disallowing_pms_from_actor?(target_user4.id)).to eq(true)+ expect(screener.disallowing_pms_from_actor?(target_user4.id)).to eq(true)endit "returns false for a user allowing only PMs for certain users which the actor allowed" dotarget_user4.user_option.update!(enable_allowed_pm_users: true)AllowedPmUser.create!(user: target_user4, allowed_pm_user: acting_user)- expect(subject.disallowing_pms_from_actor?(target_user4.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user4.id)).to eq(false)endit "returns false for a user not disallowing PMs or muting or ignoring" do- expect(subject.disallowing_pms_from_actor?(target_user5.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user5.id)).to eq(false)endit "returns true for a user not disallowing PMs but still ignoring" do- expect(subject.disallowing_pms_from_actor?(target_user1.id)).to eq(true)+ expect(screener.disallowing_pms_from_actor?(target_user1.id)).to eq(true)endit "returns true for a user not disallowing PMs but still muting" do- expect(subject.disallowing_pms_from_actor?(target_user2.id)).to eq(true)+ expect(screener.disallowing_pms_from_actor?(target_user2.id)).to eq(true)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.disallowing_pms_from_actor?(other_user.id) }.to raise_error(+ expect { screener.disallowing_pms_from_actor?(other_user.id) }.to raise_error(Discourse::NotFound,)end@@ -146,7 +146,7 @@ RSpec.describe UserCommScreener dodescribe "#allowing_actor_communication" doit "returns all usernames since staff can communicate with anyone" do- expect(subject.allowing_actor_communication).to match_array(+ expect(screener.allowing_actor_communication).to match_array([target_user1.id, target_user2.id, target_user3.id, target_user4.id, target_user5.id],)end@@ -154,25 +154,25 @@ RSpec.describe UserCommScreener dodescribe "#preventing_actor_communication" doit "does not return any usernames since no users can prevent staff communicating with them" do- expect(subject.preventing_actor_communication).to eq([])+ expect(screener.preventing_actor_communication).to eq([])endenddescribe "#ignoring_or_muting_actor?" doit "returns false for a user muting the staff" do- expect(subject.ignoring_or_muting_actor?(target_user1.id)).to eq(false)+ expect(screener.ignoring_or_muting_actor?(target_user1.id)).to eq(false)endit "returns false for a user ignoring the staff actor" do- expect(subject.ignoring_or_muting_actor?(target_user2.id)).to eq(false)+ expect(screener.ignoring_or_muting_actor?(target_user2.id)).to eq(false)endit "returns false for a user neither ignoring or muting the actor" do- expect(subject.ignoring_or_muting_actor?(target_user3.id)).to eq(false)+ expect(screener.ignoring_or_muting_actor?(target_user3.id)).to eq(false)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.ignoring_or_muting_actor?(other_user.id) }.to raise_error(+ expect { screener.ignoring_or_muting_actor?(other_user.id) }.to raise_error(Discourse::NotFound,)end@@ -180,28 +180,28 @@ RSpec.describe UserCommScreener dodescribe "#disallowing_pms_from_actor?" doit "returns false for a user disallowing all PMs" do- expect(subject.disallowing_pms_from_actor?(target_user3.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user3.id)).to eq(false)endit "returns false for a user allowing only PMs for certain users but not the actor" dotarget_user4.user_option.update!(enable_allowed_pm_users: true)- expect(subject.disallowing_pms_from_actor?(target_user4.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user4.id)).to eq(false)endit "returns false for a user not disallowing PMs or muting or ignoring" do- expect(subject.disallowing_pms_from_actor?(target_user5.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user5.id)).to eq(false)endit "returns false for a user not disallowing PMs but still ignoring" do- expect(subject.disallowing_pms_from_actor?(target_user1.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user1.id)).to eq(false)endit "returns false for a user not disallowing PMs but still muting" do- expect(subject.disallowing_pms_from_actor?(target_user2.id)).to eq(false)+ expect(screener.disallowing_pms_from_actor?(target_user2.id)).to eq(false)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.disallowing_pms_from_actor?(other_user.id) }.to raise_error(+ expect { screener.disallowing_pms_from_actor?(other_user.id) }.to raise_error(Discourse::NotFound,)end@@ -232,13 +232,13 @@ RSpec.describe UserCommScreener dodescribe "#actor_preventing_communication" doit "returns the user_ids of the users the actor is ignoring, muting, or disallowing PMs from" doacting_user.user_option.update!(enable_allowed_pm_users: true)- expect(subject.actor_preventing_communication).to match_array(+ expect(screener.actor_preventing_communication).to match_array([target_user1.id, target_user2.id, target_user3.id, target_user5.id],)endit "does not include users the actor is disallowing PMs from if they have not set enable_allowed_pm_users" do- expect(subject.actor_preventing_communication).to match_array(+ expect(screener.actor_preventing_communication).to match_array([target_user1.id, target_user2.id],)end@@ -250,7 +250,7 @@ RSpec.describe UserCommScreener doendit "returns an empty array and does not error" do- expect(subject.actor_preventing_communication).to match_array([])+ expect(screener.actor_preventing_communication).to match_array([])endendend@@ -258,7 +258,7 @@ RSpec.describe UserCommScreener dodescribe "#actor_allowing_communication" doit "returns the user_ids of the users who the actor is not ignoring, muting, or disallowing PMs from" doacting_user.user_option.update!(enable_allowed_pm_users: true)- expect(subject.actor_allowing_communication).to match_array([target_user4.id])+ expect(screener.actor_allowing_communication).to match_array([target_user4.id])enddescribe "when the actor has no preferences" do@@ -268,7 +268,7 @@ RSpec.describe UserCommScreener doendit "returns an array of the target users and does not error" do- expect(subject.actor_allowing_communication).to match_array(+ expect(screener.actor_allowing_communication).to match_array([target_user1.id, target_user2.id, target_user3.id, target_user4.id, target_user5.id],)end@@ -277,49 +277,51 @@ RSpec.describe UserCommScreener dodescribe "#actor_ignoring?" doit "returns true for user ids that the actor is ignoring" do- expect(subject.actor_ignoring?(target_user2.id)).to eq(true)- expect(subject.actor_ignoring?(target_user4.id)).to eq(false)+ expect(screener.actor_ignoring?(target_user2.id)).to eq(true)+ expect(screener.actor_ignoring?(target_user4.id)).to eq(false)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.actor_ignoring?(other_user.id) }.to raise_error(Discourse::NotFound)+ expect { screener.actor_ignoring?(other_user.id) }.to raise_error(Discourse::NotFound)endenddescribe "#actor_muting?" doit "returns true for user ids that the actor is muting" do- expect(subject.actor_muting?(target_user1.id)).to eq(true)- expect(subject.actor_muting?(target_user2.id)).to eq(false)+ expect(screener.actor_muting?(target_user1.id)).to eq(true)+ expect(screener.actor_muting?(target_user2.id)).to eq(false)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.actor_muting?(other_user.id) }.to raise_error(Discourse::NotFound)+ expect { screener.actor_muting?(other_user.id) }.to raise_error(Discourse::NotFound)endenddescribe "#actor_disallowing_pms?" doit "returns true for user ids that the actor is not explicitly allowing PMs from" doacting_user.user_option.update!(enable_allowed_pm_users: true)- expect(subject.actor_disallowing_pms?(target_user3.id)).to eq(true)- expect(subject.actor_disallowing_pms?(target_user1.id)).to eq(false)+ expect(screener.actor_disallowing_pms?(target_user3.id)).to eq(true)+ expect(screener.actor_disallowing_pms?(target_user1.id)).to eq(false)endit "returns true if the actor has disallowed all PMs" doacting_user.user_option.update!(allow_private_messages: false)- expect(subject.actor_disallowing_pms?(target_user3.id)).to eq(true)- expect(subject.actor_disallowing_pms?(target_user1.id)).to eq(true)+ expect(screener.actor_disallowing_pms?(target_user3.id)).to eq(true)+ expect(screener.actor_disallowing_pms?(target_user1.id)).to eq(true)endit "raises a NotFound error if the user_id passed in is not part of the target users" do- expect { subject.actor_disallowing_pms?(other_user.id) }.to raise_error(Discourse::NotFound)+ expect { screener.actor_disallowing_pms?(other_user.id) }.to raise_error(+ Discourse::NotFound,+ )endenddescribe "#actor_disallowing_all_pms?" doit "returns true if the acting user has disabled private messages altogether" do- expect(subject.actor_disallowing_all_pms?).to eq(false)+ expect(screener.actor_disallowing_all_pms?).to eq(false)acting_user.user_option.update!(allow_private_messages: false)- expect(subject.actor_disallowing_all_pms?).to eq(true)+ expect(screener.actor_disallowing_all_pms?).to eq(true)endendenddiff --git a/spec/lib/validators/allowed_ip_address_validator_spec.rb b/spec/lib/validators/allowed_ip_address_validator_spec.rbindex 03f176293a4..5f9c31b6166 100644--- a/spec/lib/validators/allowed_ip_address_validator_spec.rb+++ b/spec/lib/validators/allowed_ip_address_validator_spec.rb@@ -1,9 +1,10 @@# frozen_string_literal: trueRSpec.describe AllowedIpAddressValidator do+ subject(:validate) { validator.validate_each(record, :ip_address, record.ip_address) }+let(:record) { Fabricate.build(:user, trust_level: TrustLevel[0], ip_address: "99.232.23.123") }let(:validator) { described_class.new(attributes: :ip_address) }- subject(:validate) { validator.validate_each(record, :ip_address, record.ip_address) }context "when ip address should be blocked" doit "should add an error" dodiff --git a/spec/lib/validators/css_color_validator_spec.rb b/spec/lib/validators/css_color_validator_spec.rbindex 115531e40b8..acec8e18920 100644--- a/spec/lib/validators/css_color_validator_spec.rb+++ b/spec/lib/validators/css_color_validator_spec.rb@@ -1,21 +1,21 @@# frozen_string_literal: trueRSpec.describe CssColorValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }it "validates hex colors" do- expect(subject.valid_value?("#0")).to eq(false)- expect(subject.valid_value?("#00")).to eq(false)- expect(subject.valid_value?("#000")).to eq(true)- expect(subject.valid_value?("#0000")).to eq(false)- expect(subject.valid_value?("#00000")).to eq(false)- expect(subject.valid_value?("#000000")).to eq(true)+ expect(validator.valid_value?("#0")).to eq(false)+ expect(validator.valid_value?("#00")).to eq(false)+ expect(validator.valid_value?("#000")).to eq(true)+ expect(validator.valid_value?("#0000")).to eq(false)+ expect(validator.valid_value?("#00000")).to eq(false)+ expect(validator.valid_value?("#000000")).to eq(true)endit "validates css colors" do- expect(subject.valid_value?("red")).to eq(true)- expect(subject.valid_value?("green")).to eq(true)- expect(subject.valid_value?("blue")).to eq(true)- expect(subject.valid_value?("hello")).to eq(false)+ expect(validator.valid_value?("red")).to eq(true)+ expect(validator.valid_value?("green")).to eq(true)+ expect(validator.valid_value?("blue")).to eq(true)+ expect(validator.valid_value?("hello")).to eq(false)endenddiff --git a/spec/lib/validators/enable_local_logins_via_email_validator_spec.rb b/spec/lib/validators/enable_local_logins_via_email_validator_spec.rbindex 8469aae93a0..ff68d47a608 100644--- a/spec/lib/validators/enable_local_logins_via_email_validator_spec.rb+++ b/spec/lib/validators/enable_local_logins_via_email_validator_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe EnableLocalLoginsViaEmailValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }describe "#valid_value?" dodescribe "when 'enable_local_logins' is false" do@@ -9,15 +9,15 @@ RSpec.describe EnableLocalLoginsViaEmailValidator dodescribe "when val is false" doit "should be valid" do- expect(subject.valid_value?("f")).to eq(true)+ expect(validator.valid_value?("f")).to eq(true)endenddescribe "when value is true" doit "should not be valid" do- expect(subject.valid_value?("t")).to eq(false)+ expect(validator.valid_value?("t")).to eq(false)- expect(subject.error_message).to eq(+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.enable_local_logins_disabled"),)end@@ -29,13 +29,13 @@ RSpec.describe EnableLocalLoginsViaEmailValidator dodescribe "when val is false" doit "should be valid" do- expect(subject.valid_value?("f")).to eq(true)+ expect(validator.valid_value?("f")).to eq(true)endenddescribe "when value is true" doit "should be valid" do- expect(subject.valid_value?("t")).to eq(true)+ expect(validator.valid_value?("t")).to eq(true)endendenddiff --git a/spec/lib/validators/enable_sso_validator_spec.rb b/spec/lib/validators/enable_sso_validator_spec.rbindex edbdb21c474..c6ff325701f 100644--- a/spec/lib/validators/enable_sso_validator_spec.rb+++ b/spec/lib/validators/enable_sso_validator_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe EnableSsoValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }describe "#valid_value?" dodescribe "when 'sso url' is empty" do@@ -9,15 +9,15 @@ RSpec.describe EnableSsoValidator dodescribe "when val is false" doit "should be valid" do- expect(subject.valid_value?("f")).to eq(true)+ expect(validator.valid_value?("f")).to eq(true)endenddescribe "when value is true" doit "should not be valid" do- expect(subject.valid_value?("t")).to eq(false)+ expect(validator.valid_value?("t")).to eq(false)- expect(subject.error_message).to eq(+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.discourse_connect_url_is_empty"),)end@@ -29,13 +29,13 @@ RSpec.describe EnableSsoValidator dodescribe "when value is false" doit "should be valid" do- expect(subject.valid_value?("f")).to eq(true)+ expect(validator.valid_value?("f")).to eq(true)endenddescribe "when value is true" doit "should be valid" do- expect(subject.valid_value?("t")).to eq(true)+ expect(validator.valid_value?("t")).to eq(true)endendend@@ -46,13 +46,13 @@ RSpec.describe EnableSsoValidator doit "should be invalid" doSiteSetting.enforce_second_factor = "all"- expect(subject.valid_value?("t")).to eq(false)+ expect(validator.valid_value?("t")).to eq(false)endit "should be valid" doSiteSetting.enforce_second_factor = "no"- expect(subject.valid_value?("t")).to eq(true)+ expect(validator.valid_value?("t")).to eq(true)endendenddiff --git a/spec/lib/validators/external_system_avatars_validator_spec.rb b/spec/lib/validators/external_system_avatars_validator_spec.rbindex 526eaa372ce..c949238daf4 100644--- a/spec/lib/validators/external_system_avatars_validator_spec.rb+++ b/spec/lib/validators/external_system_avatars_validator_spec.rb@@ -1,25 +1,25 @@# frozen_string_literal: trueRSpec.describe ExternalSystemAvatarsValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }it "disallows disabling external system avatars when Unicode usernames are enabled" doSiteSetting.unicode_usernames = true- expect(subject.valid_value?("f")).to eq(false)- expect(subject.error_message).to eq(I18n.t("site_settings.errors.unicode_usernames_avatars"))+ expect(validator.valid_value?("f")).to eq(false)+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.unicode_usernames_avatars"))- expect(subject.valid_value?("t")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("t")).to eq(true)+ expect(validator.error_message).to be_blankendit "allows disabling external system avatars when Unicode usernames are disabled" doSiteSetting.unicode_usernames = false- expect(subject.valid_value?("t")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("t")).to eq(true)+ expect(validator.error_message).to be_blank- expect(subject.valid_value?("f")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("f")).to eq(true)+ expect(validator.error_message).to be_blankendenddiff --git a/spec/lib/validators/ip_address_format_validator_spec.rb b/spec/lib/validators/ip_address_format_validator_spec.rbindex 1e9df7db3cf..d0c5abc71bb 100644--- a/spec/lib/validators/ip_address_format_validator_spec.rb+++ b/spec/lib/validators/ip_address_format_validator_spec.rb@@ -1,9 +1,10 @@# frozen_string_literal: trueRSpec.describe IpAddressFormatValidator do+ subject(:validate) { validator.validate_each(record, :ip_address, record.ip_address) }+let(:record) { Fabricate.build(:screened_ip_address, ip_address: "99.232.23.123") }let(:validator) { described_class.new(attributes: :ip_address) }- subject(:validate) { validator.validate_each(record, :ip_address, record.ip_address) }%w[99.232.23.123 99.232.0.0/16 fd12:db8::ff00:42:8329 fc00::/7].each do |arg|it "should not add an error for #{arg}" dodiff --git a/spec/lib/validators/password_validator_spec.rb b/spec/lib/validators/password_validator_spec.rbindex eb8bc4e590a..ce27c633a8d 100644--- a/spec/lib/validators/password_validator_spec.rb+++ b/spec/lib/validators/password_validator_spec.rb@@ -5,9 +5,10 @@ RSpec.describe PasswordValidator doI18n.t("activerecord.errors.models.user.attributes.password.#{key.to_s}")end- let(:validator) { described_class.new(attributes: :password) }subject(:validate) { validator.validate_each(record, :password, @password) }+ let(:validator) { described_class.new(attributes: :password) }+describe "password required" dolet(:record) dou = Fabricate.build(:user, password: @password)diff --git a/spec/lib/validators/regex_presence_validator_spec.rb b/spec/lib/validators/regex_presence_validator_spec.rbindex 416ac83d2cc..cac2332a2aa 100644--- a/spec/lib/validators/regex_presence_validator_spec.rb+++ b/spec/lib/validators/regex_presence_validator_spec.rb@@ -1,28 +1,28 @@# frozen_string_literal: trueRSpec.describe RegexPresenceValidator do- subject do+ subject(:validator) dodescribed_class.new(regex: "latest", regex_error: "site_settings.errors.must_include_latest")enddescribe "#valid_value?" dodescribe "when value is present" doit "without regex match" do- expect(subject.valid_value?("categories|new")).to eq(false)+ expect(validator.valid_value?("categories|new")).to eq(false)- expect(subject.error_message).to eq(I18n.t("site_settings.errors.must_include_latest"))+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.must_include_latest"))endit "with regex match" do- expect(subject.valid_value?("latest|categories")).to eq(true)+ expect(validator.valid_value?("latest|categories")).to eq(true)endenddescribe "when value is empty" doit "should not be valid" do- expect(subject.valid_value?("")).to eq(false)+ expect(validator.valid_value?("")).to eq(false)- expect(subject.error_message).to eq(I18n.t("site_settings.errors.must_include_latest"))+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.must_include_latest"))endendenddiff --git a/spec/lib/validators/regexp_list_validator_spec.rb b/spec/lib/validators/regexp_list_validator_spec.rbindex fb2f816c414..98f2990f11e 100644--- a/spec/lib/validators/regexp_list_validator_spec.rb+++ b/spec/lib/validators/regexp_list_validator_spec.rb@@ -1,15 +1,15 @@# frozen_string_literal: trueRSpec.describe RegexpListValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }it "allows lists of valid regular expressions" do- expect(subject.valid_value?('\d+|[0-9]?|\w+')).to eq(true)+ expect(validator.valid_value?('\d+|[0-9]?|\w+')).to eq(true)endit "does not allow lists of invalid regular expressions do" do- expect(subject.valid_value?('\d+|[0-9?|\w+')).to eq(false)- expect(subject.error_message).to eq(+ expect(validator.valid_value?('\d+|[0-9?|\w+')).to eq(false)+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.invalid_regex_with_message",regex: "[0-9?",diff --git a/spec/lib/validators/sso_overrides_email_validator_spec.rb b/spec/lib/validators/sso_overrides_email_validator_spec.rbindex cb868e6d391..ff5623e7eec 100644--- a/spec/lib/validators/sso_overrides_email_validator_spec.rb+++ b/spec/lib/validators/sso_overrides_email_validator_spec.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueRSpec.describe SsoOverridesEmailValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }describe "#valid_value?" dodescribe "when 'email editable' is true" do@@ -13,15 +13,17 @@ RSpec.describe SsoOverridesEmailValidator dodescribe "when val is false" doit "should be valid" do- expect(subject.valid_value?("f")).to eq(true)+ expect(validator.valid_value?("f")).to eq(true)endenddescribe "when value is true" doit "should not be valid" do- expect(subject.valid_value?("t")).to eq(false)+ expect(validator.valid_value?("t")).to eq(false)- expect(subject.error_message).to eq(I18n.t("site_settings.errors.email_editable_enabled"))+ expect(validator.error_message).to eq(+ I18n.t("site_settings.errors.email_editable_enabled"),+ )endendend@@ -35,13 +37,13 @@ RSpec.describe SsoOverridesEmailValidator dodescribe "when value is false" doit "should be valid" do- expect(subject.valid_value?("f")).to eq(true)+ expect(validator.valid_value?("f")).to eq(true)endenddescribe "when value is true" doit "should be valid" do- expect(subject.valid_value?("t")).to eq(true)+ expect(validator.valid_value?("t")).to eq(true)endendenddiff --git a/spec/lib/validators/unicode_username_allowlist_validator_spec.rb b/spec/lib/validators/unicode_username_allowlist_validator_spec.rbindex de53888d05c..60d9d8131a7 100644--- a/spec/lib/validators/unicode_username_allowlist_validator_spec.rb+++ b/spec/lib/validators/unicode_username_allowlist_validator_spec.rb@@ -1,37 +1,37 @@# frozen_string_literal: trueRSpec.describe UnicodeUsernameAllowlistValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }it "allows an empty allowlist" do- expect(subject.valid_value?("")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("")).to eq(true)+ expect(validator.error_message).to be_blankendit "disallows leading and trailing slashes" doexpected_error = I18n.t("site_settings.errors.allowed_unicode_usernames.leading_trailing_slash")- expect(subject.valid_value?("/foo/")).to eq(false)- expect(subject.error_message).to eq(expected_error)+ expect(validator.valid_value?("/foo/")).to eq(false)+ expect(validator.error_message).to eq(expected_error)- expect(subject.valid_value?("foo/")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("foo/")).to eq(true)+ expect(validator.error_message).to be_blank- expect(subject.valid_value?("/foo")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("/foo")).to eq(true)+ expect(validator.error_message).to be_blank- expect(subject.valid_value?("f/o/o")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("f/o/o")).to eq(true)+ expect(validator.error_message).to be_blank- expect(subject.valid_value?("/foo/i")).to eq(false)- expect(subject.error_message).to eq(expected_error)+ expect(validator.valid_value?("/foo/i")).to eq(false)+ expect(validator.error_message).to eq(expected_error)endit "detects invalid regular expressions" doexpected_error =I18n.t("site_settings.errors.allowed_unicode_usernames.regex_invalid", error: "")- expect(subject.valid_value?("\\p{Foo}")).to eq(false)- expect(subject.error_message).to start_with(expected_error)+ expect(validator.valid_value?("\\p{Foo}")).to eq(false)+ expect(validator.error_message).to start_with(expected_error)endenddiff --git a/spec/lib/validators/unicode_username_validator_spec.rb b/spec/lib/validators/unicode_username_validator_spec.rbindex 23656f0caf4..649fca8632e 100644--- a/spec/lib/validators/unicode_username_validator_spec.rb+++ b/spec/lib/validators/unicode_username_validator_spec.rb@@ -1,25 +1,25 @@# frozen_string_literal: trueRSpec.describe UnicodeUsernameValidator do- subject { described_class.new }+ subject(:validator) { described_class.new }it "disallows Unicode usernames when external system avatars are disabled" doSiteSetting.external_system_avatars_enabled = false- expect(subject.valid_value?("t")).to eq(false)- expect(subject.error_message).to eq(I18n.t("site_settings.errors.unicode_usernames_avatars"))+ expect(validator.valid_value?("t")).to eq(false)+ expect(validator.error_message).to eq(I18n.t("site_settings.errors.unicode_usernames_avatars"))- expect(subject.valid_value?("f")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("f")).to eq(true)+ expect(validator.error_message).to be_blankendit "allows Unicode usernames when external system avatars are enabled" doSiteSetting.external_system_avatars_enabled = true- expect(subject.valid_value?("t")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("t")).to eq(true)+ expect(validator.error_message).to be_blank- expect(subject.valid_value?("f")).to eq(true)- expect(subject.error_message).to be_blank+ expect(validator.valid_value?("f")).to eq(true)+ expect(validator.error_message).to be_blankendenddiff --git a/spec/lib/validators/upload_validator_spec.rb b/spec/lib/validators/upload_validator_spec.rbindex 49fec1fef84..3f82ff8ea6c 100644--- a/spec/lib/validators/upload_validator_spec.rb+++ b/spec/lib/validators/upload_validator_spec.rb@@ -45,7 +45,7 @@ RSpec.describe UploadValidator dooriginal_filename: "test.png",filesize: 2_097_152,)- subject.validate(upload)+ validator.validate(upload)expect(upload.errors.full_messages.first).to eq("Filesize #{I18n.t("upload.images.too_large_humanized", max_size: "1.5 MB")}",)@@ -62,7 +62,7 @@ RSpec.describe UploadValidator dofor_private_message: true,)- expect(subject.validate(upload)).to eq(true)+ expect(validator.validate(upload)).to eq(true)enddescribe "for a normal user" do@@ -75,7 +75,7 @@ RSpec.describe UploadValidator dofor_private_message: true,)- expect(subject.validate(upload)).to eq(nil)+ expect(validator.validate(upload)).to eq(nil)endendend@@ -91,13 +91,13 @@ RSpec.describe UploadValidator dodescribe "for admin user" doit "should allow the upload" do- expect(subject.validate(upload)).to eq(true)+ expect(validator.validate(upload)).to eq(true)enddescribe "when filename is invalid" doit "should not allow the upload" doupload.original_filename = "test.txt"- expect(subject.validate(upload)).to eq(nil)+ expect(validator.validate(upload)).to eq(nil)endendend@@ -106,7 +106,7 @@ RSpec.describe UploadValidator dofab!(:user) { Fabricate(:user) }it "should not allow the upload" do- expect(subject.validate(upload)).to eq(nil)+ expect(validator.validate(upload)).to eq(nil)endendenddiff --git a/spec/lib/validators/url_validator_spec.rb b/spec/lib/validators/url_validator_spec.rbindex 071c3ae939f..1e763f29e77 100644--- a/spec/lib/validators/url_validator_spec.rb+++ b/spec/lib/validators/url_validator_spec.rb@@ -1,9 +1,10 @@# frozen_string_literal: trueRSpec.describe UrlValidator do+ subject(:validate) { validator.validate_each(record, :website, record.website) }+let(:record) { Fabricate.build(:user_profile, user: Fabricate.build(:user)) }let(:validator) { described_class.new(attributes: :website) }- subject(:validate) { validator.validate_each(record, :website, record.website) }["http://https://google.com",diff --git a/spec/lib/validators/user_full_name_validator_spec.rb b/spec/lib/validators/user_full_name_validator_spec.rbindex c25472fd6b3..9fcbb551ec1 100644--- a/spec/lib/validators/user_full_name_validator_spec.rb+++ b/spec/lib/validators/user_full_name_validator_spec.rb@@ -1,8 +1,9 @@# frozen_string_literal: trueRSpec.describe UserFullNameValidator do- let(:validator) { described_class.new(attributes: :name) }subject(:validate) { validator.validate_each(record, :name, @name) }++ let(:validator) { described_class.new(attributes: :name) }let(:record) { Fabricate.build(:user, name: @name) }context "when name is not required" dodiff --git a/spec/lib/webauthn/security_key_authentication_service_spec.rb b/spec/lib/webauthn/security_key_authentication_service_spec.rbindex e159119d061..3ca7e5bc91d 100644--- a/spec/lib/webauthn/security_key_authentication_service_spec.rb+++ b/spec/lib/webauthn/security_key_authentication_service_spec.rb@@ -38,6 +38,8 @@ require "webauthn/security_key_registration_service"# The origin params just need to be whatever your localhost URL for Discourse is.RSpec.describe Webauthn::SecurityKeyAuthenticationService do+ subject(:service) { described_class.new(current_user, params, challenge_params) }+let(:security_key_user) { current_user }let!(:security_key) doFabricate(@@ -91,24 +93,23 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:challenge_params_origin) { "http://localhost:3000" }let(:challenge_params) { { challenge: challenge, rp_id: rp_id, origin: challenge_params_origin } }let(:current_user) { Fabricate(:user) }- let(:subject) { described_class.new(current_user, params, challenge_params) }it "updates last_used when the security key and params are valid" do- expect(subject.authenticate_security_key).to eq(true)+ expect(service.authenticate_security_key).to eq(true)expect(security_key.reload.last_used).not_to eq(nil)endcontext "when params is blank" dolet(:params) { nil }it "returns false with no validation" do- expect(subject.authenticate_security_key).to eq(false)+ expect(service.authenticate_security_key).to eq(false)endendcontext "when params is not blank and not a hash" dolet(:params) { "test" }it "returns false with no validation" do- expect(subject.authenticate_security_key).to eq(false)+ expect(service.authenticate_security_key).to eq(false)endend@@ -116,7 +117,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dobefore { security_key.destroy }it "raises a NotFoundError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::NotFoundError,I18n.t("webauthn.validation.not_found_error"),)@@ -127,7 +128,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:security_key_user) { Fabricate(:user) }it "raises an OwnershipError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::OwnershipError,I18n.t("webauthn.validation.ownership_error"),)@@ -138,7 +139,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:client_data_webauthn_type) { "webauthn.explode" }it "raises an InvalidTypeError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::InvalidTypeError,I18n.t("webauthn.validation.invalid_type_error"),)@@ -149,7 +150,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:client_data_challenge) { Base64.strict_encode64("invalid challenge") }it "raises a ChallengeMismatchError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::ChallengeMismatchError,I18n.t("webauthn.validation.challenge_mismatch_error"),)@@ -160,7 +161,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:client_data_origin) { "https://someothersite.com" }it "raises a InvalidOriginError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::InvalidOriginError,I18n.t("webauthn.validation.invalid_origin_error"),)@@ -171,7 +172,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:rp_id) { "bad_rp_id" }it "raises a InvalidRelyingPartyIdError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::InvalidRelyingPartyIdError,I18n.t("webauthn.validation.invalid_relying_party_id_error"),)@@ -182,7 +183,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dolet(:signature) { Base64.strict_encode64("badsig") }it "raises a PublicKeyError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::PublicKeyError,I18n.t("webauthn.validation.public_key_error"),)@@ -193,7 +194,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService dobefore { COSE::Algorithm.expects(:find).returns(nil) }it "raises a UnknownCOSEAlgorithmError" do- expect { subject.authenticate_security_key }.to raise_error(+ expect { service.authenticate_security_key }.to raise_error(Webauthn::UnknownCOSEAlgorithmError,I18n.t("webauthn.validation.unknown_cose_algorithm_error"),)@@ -230,7 +231,7 @@ RSpec.describe Webauthn::SecurityKeyAuthenticationService doendit "updates last_used when the security key and params are valid" do- expect(subject.authenticate_security_key).to eq(true)+ expect(service.authenticate_security_key).to eq(true)expect(security_key.reload.last_used).not_to eq(nil)endenddiff --git a/spec/lib/webauthn/security_key_registration_service_spec.rb b/spec/lib/webauthn/security_key_registration_service_spec.rbindex 15abc16019e..45d78c516e1 100644--- a/spec/lib/webauthn/security_key_registration_service_spec.rb+++ b/spec/lib/webauthn/security_key_registration_service_spec.rb@@ -3,6 +3,8 @@ require "webauthn"require "webauthn/security_key_registration_service"RSpec.describe Webauthn::SecurityKeyRegistrationService do+ subject(:service) { described_class.new(current_user, params, challenge_params) }+let(:client_data_challenge) { Base64.encode64(challenge) }let(:client_data_webauthn_type) { "webauthn.create" }let(:client_data_origin) { "http://localhost:3000" }@@ -34,13 +36,12 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService dolet(:challenge_params) { { challenge: challenge, rp_id: rp_id, origin: "http://localhost:3000" } }let(:challenge) { "f1e04530f34a1b6a08d032d8550e23eb8330be04e4166008f26c0e1b42ad" }let(:current_user) { Fabricate(:user) }- let(:subject) { described_class.new(current_user, params, challenge_params) }context "when the client data webauthn type is not webauthn.create" dolet(:client_data_webauthn_type) { "webauthn.explode" }it "raises an InvalidTypeError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::InvalidTypeError,I18n.t("webauthn.validation.invalid_type_error"),)@@ -51,7 +52,7 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService dolet(:client_data_challenge) { Base64.encode64("invalid challenge") }it "raises a ChallengeMismatchError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::ChallengeMismatchError,I18n.t("webauthn.validation.challenge_mismatch_error"),)@@ -62,7 +63,7 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService dolet(:client_data_origin) { "https://someothersite.com" }it "raises a InvalidOriginError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::InvalidOriginError,I18n.t("webauthn.validation.invalid_origin_error"),)@@ -73,7 +74,7 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService dolet(:rp_id) { "bad_rp_id" }it "raises a InvalidRelyingPartyIdError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::InvalidRelyingPartyIdError,I18n.t("webauthn.validation.invalid_relying_party_id_error"),)@@ -87,7 +88,7 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService doendit "raises a UnsupportedPublicKeyAlgorithmError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::UnsupportedPublicKeyAlgorithmError,I18n.t("webauthn.validation.unsupported_public_key_algorithm_error"),)@@ -103,7 +104,7 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService doendit "raises a UnsupportedAttestationFormatError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::UnsupportedAttestationFormatError,I18n.t("webauthn.validation.unsupported_attestation_format_error"),)@@ -117,14 +118,14 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService docontext "when the credential id is already in use for any user" doit "raises a CredentialIdInUseError" do# register the key to the current user- security_key = subject.register_second_factor_security_key+ security_key = service.register_second_factor_security_key# update the key to be on a different userother_user = Fabricate(:user)security_key.update(user: other_user)# error!- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::CredentialIdInUseError,I18n.t("webauthn.validation.credential_id_in_use_error"),)@@ -137,7 +138,7 @@ RSpec.describe Webauthn::SecurityKeyRegistrationService doendit "raises a MalformedAttestationError" do- expect { subject.register_second_factor_security_key }.to raise_error(+ expect { service.register_second_factor_security_key }.to raise_error(Webauthn::MalformedAttestationError,I18n.t("webauthn.validation.malformed_attestation_error"),)diff --git a/spec/mailers/subscription_mailer_spec.rb b/spec/mailers/subscription_mailer_spec.rbindex e61e0657380..fff84e4c534 100644--- a/spec/mailers/subscription_mailer_spec.rb+++ b/spec/mailers/subscription_mailer_spec.rb@@ -1,12 +1,12 @@# frozen_string_literal: trueRSpec.describe SubscriptionMailer do- fab!(:user) { Fabricate(:user) }+ subject(:mail) { SubscriptionMailer.confirm_unsubscribe(user) }- subject { SubscriptionMailer.confirm_unsubscribe(user) }+ fab!(:user) { Fabricate(:user) }it "contains the right URL" do- expect(subject.body).to include(+ expect(mail.body).to include("#{Discourse.base_url}/email/unsubscribe/#{UnsubscribeKey.last.key}",)enddiff --git a/spec/mailers/user_notifications_spec.rb b/spec/mailers/user_notifications_spec.rbindex 1482d04213e..f9589fffb54 100644--- a/spec/mailers/user_notifications_spec.rb+++ b/spec/mailers/user_notifications_spec.rb@@ -58,24 +58,24 @@ RSpec.describe UserNotifications doenddescribe ".signup" do- subject { UserNotifications.signup(user) }+ subject(:email) { UserNotifications.signup(user) }it "works" do- expect(subject.to).to eq([user.email])- expect(subject.subject).to be_present- expect(subject.from).to eq([SiteSetting.notification_email])- expect(subject.body).to be_present+ expect(email.to).to eq([user.email])+ expect(email.subject).to be_present+ expect(email.from).to eq([SiteSetting.notification_email])+ expect(email.body).to be_presentendenddescribe ".forgot_password" do- subject { UserNotifications.forgot_password(user) }+ subject(:email) { UserNotifications.forgot_password(user) }it "works" do- expect(subject.to).to eq([user.email])- expect(subject.subject).to be_present- expect(subject.from).to eq([SiteSetting.notification_email])- expect(subject.body).to be_present+ expect(email.to).to eq([user.email])+ expect(email.subject).to be_present+ expect(email.from).to eq([SiteSetting.notification_email])+ expect(email.body).to be_presentendend@@ -119,20 +119,21 @@ RSpec.describe UserNotifications doenddescribe ".email_login" do+ subject(:email) { UserNotifications.email_login(user, email_token: email_token) }+let(:email_token) doFabricate(:email_token, user: user, scope: EmailToken.scopes[:email_login]).tokenend- subject { UserNotifications.email_login(user, email_token: email_token) }it "generates the right email" do- expect(subject.to).to eq([user.email])- expect(subject.from).to eq([SiteSetting.notification_email])+ expect(email.to).to eq([user.email])+ expect(email.from).to eq([SiteSetting.notification_email])- expect(subject.subject).to eq(+ expect(email.subject).to eq(I18n.t("user_notifications.email_login.subject_template", email_prefix: SiteSetting.title),)- expect(subject.body.to_s).to match(+ expect(email.body.to_s).to match(I18n.t("user_notifications.email_login.text_body_template",site_name: SiteSetting.title,@@ -144,13 +145,13 @@ RSpec.describe UserNotifications doenddescribe ".digest" do- subject { UserNotifications.digest(user) }+ subject(:email) { UserNotifications.digest(user) }after { Discourse.redis.keys("summary-new-users:*").each { |key| Discourse.redis.del(key) } }context "without new topics" doit "doesn't send the email" do- expect(subject.to).to be_blank+ expect(email.to).to be_blankendend@@ -172,8 +173,8 @@ RSpec.describe UserNotifications doendit "returns topics from new users if they're more than 24 hours old" do- expect(subject.to).to eq([user.email])- html = subject.html_part.body.to_s+ expect(email.to).to eq([user.email])+ html = email.html_part.body.to_sexpect(html).to include(new_yesterday.title)expect(html).to_not include(new_today.title)end@@ -185,18 +186,18 @@ RSpec.describe UserNotifications doendit "works" do- expect(subject.to).to eq([user.email])- expect(subject.subject).to be_present- expect(subject.from).to eq([SiteSetting.notification_email])- expect(subject.html_part.body.to_s).to be_present- expect(subject.text_part.body.to_s).to be_present- expect(subject.header["List-Unsubscribe"].to_s).to match(/\/email\/unsubscribe\/\h{64}/)- expect(subject.html_part.body.to_s).to include("New Users")+ expect(email.to).to eq([user.email])+ expect(email.subject).to be_present+ expect(email.from).to eq([SiteSetting.notification_email])+ expect(email.html_part.body.to_s).to be_present+ expect(email.text_part.body.to_s).to be_present+ expect(email.header["List-Unsubscribe"].to_s).to match(/\/email\/unsubscribe\/\h{64}/)+ expect(email.html_part.body.to_s).to include("New Users")endit "doesn't include new user count if digest_after_minutes is low" douser.user_option.digest_after_minutes = 60- expect(subject.html_part.body.to_s).to_not include("New Users")+ expect(email.html_part.body.to_s).to_not include("New Users")endit "works with min_date string" do@@ -210,8 +211,8 @@ RSpec.describe UserNotifications doSiteSetting.email_prefix = "Try Discourse"SiteSetting.title = "Discourse Meta"- expect(subject.subject).to match(/Try Discourse/)- expect(subject.subject).not_to match(/Discourse Meta/)+ expect(email.subject).to match(/Try Discourse/)+ expect(email.subject).not_to match(/Discourse Meta/)endit "includes unread likes received count within the since date" do@@ -257,7 +258,7 @@ RSpec.describe UserNotifications docreated_at: 1.hour.ago,)deleted.trash!- html = subject.html_part.body.to_s+ html = email.html_part.body.to_sexpect(html).to_not include deleted.titleexpect(html).to_not include post.rawend@@ -276,7 +277,7 @@ RSpec.describe UserNotifications doraw: "secret draft content",created_at: 1.hour.ago,)- html = subject.html_part.body.to_s+ html = email.html_part.body.to_sexpect(html).to_not include topic.titleexpect(html).to_not include post.rawend@@ -319,7 +320,7 @@ RSpec.describe UserNotifications dopost_type: Post.types[:small_action],created_at: 1.hour.ago,)- html = subject.html_part.body.to_s+ html = email.html_part.body.to_sexpect(html).to_not include whisper.rawexpect(html).to_not include mod_action.rawexpect(html).to_not include small_action.raw@@ -365,7 +366,7 @@ RSpec.describe UserNotifications douser_deleted: true,created_at: 1.hour.ago,)- html = subject.html_part.body.to_s+ html = email.html_part.body.to_sexpect(html).to_not include deleted.rawexpect(html).to_not include hidden.rawexpect(html).to_not include user_deleted.raw@@ -389,7 +390,7 @@ RSpec.describe UserNotifications dopost_number: 1,created_at: 1.minute.ago,)- html = subject.html_part.body.to_s+ html = email.html_part.body.to_sexpect(html).to_not include too_new.titleend@@ -408,20 +409,20 @@ RSpec.describe UserNotifications dotheme.set_default!- html = subject.html_part.body.to_s+ html = email.html_part.body.to_sexpect(html).to include "F0F0F0"expect(html).to include "1E1E1E"endit "supports subfolder" doset_subfolder "/forum"- html = subject.html_part.body.to_s- text = subject.text_part.body.to_s+ html = email.html_part.body.to_s+ text = email.text_part.body.to_sexpect(html).to be_presentexpect(text).to be_presentexpect(html).to_not include("/forum/forum")expect(text).to_not include("/forum/forum")- expect(subject.header["List-Unsubscribe"].to_s).to match(+ expect(email.header["List-Unsubscribe"].to_s).to match(/http:\/\/test.localhost\/forum\/email\/unsubscribe\/\h{64}/,)@@ -432,7 +433,7 @@ RSpec.describe UserNotifications doit "applies lang/xml:lang html attributes" doSiteSetting.default_locale = "pl_PL"- html = subject.html_part.to_s+ html = email.html_part.to_sexpect(html).to match(' lang="pl-PL"')expect(html).to match(' xml:lang="pl-PL"')diff --git a/spec/mailers/version_mailer_spec.rb b/spec/mailers/version_mailer_spec.rbindex 59c047ba9d4..9e2da3c2203 100644--- a/spec/mailers/version_mailer_spec.rb+++ b/spec/mailers/version_mailer_spec.rb@@ -1,13 +1,13 @@# frozen_string_literal: trueRSpec.describe VersionMailer do- subject { VersionMailer.send_notice }+ subject(:mail) { VersionMailer.send_notice }context "when contact_email is blank" dobefore { SiteSetting.contact_email = "" }it "doesn't send the email" do- expect(subject.to).to be_blank+ expect(mail.to).to be_blankendend@@ -15,10 +15,10 @@ RSpec.describe VersionMailer dobefore { SiteSetting.contact_email = "[email protected]" }it "works" do- expect(subject.to).to eq(["[email protected]"])- expect(subject.subject).to be_present- expect(subject.from).to eq([SiteSetting.notification_email])- expect(subject.body).to be_present+ expect(mail.to).to eq(["[email protected]"])+ expect(mail.subject).to be_present+ expect(mail.from).to eq([SiteSetting.notification_email])+ expect(mail.body).to be_presentendendenddiff --git a/spec/models/admin_dashboard_data_spec.rb b/spec/models/admin_dashboard_data_spec.rbindex 7dc061cebbc..bc7b947e5b5 100644--- a/spec/models/admin_dashboard_data_spec.rb+++ b/spec/models/admin_dashboard_data_spec.rb@@ -126,93 +126,93 @@ RSpec.describe AdminDashboardData doenddescribe "rails_env_check" do- subject { described_class.new.rails_env_check }+ subject(:check) { described_class.new.rails_env_check }it "returns nil when running in production mode" doRails.stubs(env: ActiveSupport::StringInquirer.new("production"))- expect(subject).to be_nil+ expect(check).to be_nilendit "returns a string when running in development mode" doRails.stubs(env: ActiveSupport::StringInquirer.new("development"))- expect(subject).to_not be_nil+ expect(check).to_not be_nilendit "returns a string when running in test mode" doRails.stubs(env: ActiveSupport::StringInquirer.new("test"))- expect(subject).to_not be_nil+ expect(check).to_not be_nilendenddescribe "host_names_check" do- subject { described_class.new.host_names_check }+ subject(:check) { described_class.new.host_names_check }it "returns nil when host_names is set" doDiscourse.stubs(:current_hostname).returns("something.com")- expect(subject).to be_nil+ expect(check).to be_nilendit "returns a string when host_name is localhost" doDiscourse.stubs(:current_hostname).returns("localhost")- expect(subject).to_not be_nil+ expect(check).to_not be_nilendit "returns a string when host_name is production.localhost" doDiscourse.stubs(:current_hostname).returns("production.localhost")- expect(subject).to_not be_nil+ expect(check).to_not be_nilendenddescribe "sidekiq_check" do- subject { described_class.new.sidekiq_check }+ subject(:check) { described_class.new.sidekiq_check }it "returns nil when sidekiq processed a job recently" doJobs.stubs(:last_job_performed_at).returns(1.minute.ago)Jobs.stubs(:queued).returns(0)- expect(subject).to be_nil+ expect(check).to be_nilendit "returns nil when last job processed was a long time ago, but no jobs are queued" doJobs.stubs(:last_job_performed_at).returns(7.days.ago)Jobs.stubs(:queued).returns(0)- expect(subject).to be_nil+ expect(check).to be_nilendit "returns nil when no jobs have ever been processed, but no jobs are queued" doJobs.stubs(:last_job_performed_at).returns(nil)Jobs.stubs(:queued).returns(0)- expect(subject).to be_nil+ expect(check).to be_nilendit "returns a string when no jobs were processed recently and some jobs are queued" doJobs.stubs(:last_job_performed_at).returns(20.minutes.ago)Jobs.stubs(:queued).returns(1)- expect(subject).to_not be_nil+ expect(check).to_not be_nilendit "returns a string when no jobs have ever been processed, and some jobs are queued" doJobs.stubs(:last_job_performed_at).returns(nil)Jobs.stubs(:queued).returns(1)- expect(subject).to_not be_nil+ expect(check).to_not be_nilendenddescribe "ram_check" do- subject { described_class.new.ram_check }+ subject(:check) { described_class.new.ram_check }it "returns nil when total ram is 1 GB" doMemInfo.any_instance.stubs(:mem_total).returns(1_025_272)- expect(subject).to be_nil+ expect(check).to be_nilendit "returns nil when total ram cannot be determined" doMemInfo.any_instance.stubs(:mem_total).returns(nil)- expect(subject).to be_nil+ expect(check).to be_nilendit "returns a string when total ram is less than 1 GB" doMemInfo.any_instance.stubs(:mem_total).returns(512_636)- expect(subject).to_not be_nil+ expect(check).to_not be_nilendend@@ -221,7 +221,7 @@ RSpec.describe AdminDashboardData docontext "when disabled" doit "returns nil" doSiteSetting.set(enable_setting, false)- expect(subject).to be_nil+ expect(check).to be_nilendend@@ -231,31 +231,32 @@ RSpec.describe AdminDashboardData doit "returns nil when key and secret are set" doSiteSetting.set(key, "12313213")SiteSetting.set(secret, "12312313123")- expect(subject).to be_nil+ expect(check).to be_nilendit "returns a string when key is not set" doSiteSetting.set(key, "")SiteSetting.set(secret, "12312313123")- expect(subject).to_not be_nil+ expect(check).to_not be_nilendit "returns a string when secret is not set" doSiteSetting.set(key, "123123")SiteSetting.set(secret, "")- expect(subject).to_not be_nil+ expect(check).to_not be_nilendit "returns a string when key and secret are not set" doSiteSetting.set(key, "")SiteSetting.set(secret, "")- expect(subject).to_not be_nil+ expect(check).to_not be_nilendendenddescribe "facebook" do- subject { described_class.new.facebook_config_check }+ subject(:check) { described_class.new.facebook_config_check }+let(:enable_setting) { :enable_facebook_logins }let(:key) { :facebook_app_id }let(:secret) { :facebook_app_secret }@@ -263,7 +264,8 @@ RSpec.describe AdminDashboardData doenddescribe "twitter" do- subject { described_class.new.twitter_config_check }+ subject(:check) { described_class.new.twitter_config_check }+let(:enable_setting) { :enable_twitter_logins }let(:key) { :twitter_consumer_key }let(:secret) { :twitter_consumer_secret }@@ -271,7 +273,8 @@ RSpec.describe AdminDashboardData doenddescribe "github" do- subject { described_class.new.github_config_check }+ subject(:check) { described_class.new.github_config_check }+let(:enable_setting) { :enable_github_logins }let(:key) { :github_client_id }let(:secret) { :github_client_secret }@@ -280,28 +283,28 @@ RSpec.describe AdminDashboardData doenddescribe "force_https_check" do- subject { described_class.new(check_force_https: true).force_https_check }+ subject(:check) { described_class.new(check_force_https: true).force_https_check }it "returns nil if force_https site setting enabled" doSiteSetting.force_https = true- expect(subject).to be_nil+ expect(check).to be_nilendit "returns nil if force_https site setting not enabled" doSiteSetting.force_https = false- expect(subject).to eq(I18n.t("dashboard.force_https_warning", base_path: Discourse.base_path))+ expect(check).to eq(I18n.t("dashboard.force_https_warning", base_path: Discourse.base_path))endenddescribe "ignore force_https_check" do- subject { described_class.new(check_force_https: false).force_https_check }+ subject(:check) { described_class.new(check_force_https: false).force_https_check }it "returns nil" doSiteSetting.force_https = true- expect(subject).to be_nil+ expect(check).to be_nilSiteSetting.force_https = false- expect(subject).to be_nil+ expect(check).to be_nilendenddiff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rbindex d59d7abb984..8b50208fd04 100644--- a/spec/models/category_spec.rb+++ b/spec/models/category_spec.rb@@ -556,13 +556,13 @@ RSpec.describe Category doenddescribe "new" do- subject { Fabricate.build(:category, user: Fabricate(:user)) }+ subject(:category) { Fabricate.build(:category, user: Fabricate(:user)) }it "triggers a extensibility event" do- event = DiscourseEvent.track_events { subject.save! }.last+ event = DiscourseEvent.track_events { category.save! }.lastexpect(event[:event_name]).to eq(:category_created)- expect(event[:params].first).to eq(subject)+ expect(event[:params].first).to eq(category)endenddiff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rbindex 7fdbe2f74d6..4689284a524 100644--- a/spec/models/group_spec.rb+++ b/spec/models/group_spec.rb@@ -502,13 +502,13 @@ RSpec.describe Group doenddescribe "new" do- subject { Fabricate.build(:group) }+ subject(:group) { Fabricate.build(:group) }it "triggers a extensibility event" do- event = DiscourseEvent.track_events { subject.save! }.first+ event = DiscourseEvent.track_events { group.save! }.firstexpect(event[:event_name]).to eq(:group_created)- expect(event[:params].first).to eq(subject)+ expect(event[:params].first).to eq(group)endenddiff --git a/spec/models/permalink_spec.rb b/spec/models/permalink_spec.rbindex c22c49d1ad2..6e1d2c53451 100644--- a/spec/models/permalink_spec.rb+++ b/spec/models/permalink_spec.rb@@ -24,12 +24,13 @@ RSpec.describe Permalink doenddescribe "target_url" do+ subject(:target_url) { permalink.target_url }+let(:permalink) { Fabricate.build(:permalink) }let(:topic) { Fabricate(:topic) }let(:post) { Fabricate(:post, topic: topic) }let(:category) { Fabricate(:category) }let(:tag) { Fabricate(:tag) }- subject(:target_url) { permalink.target_url }it "returns a topic url when topic_id is set" dopermalink.topic_id = topic.iddiff --git a/spec/models/report_spec.rb b/spec/models/report_spec.rbindex 076d5b846ca..3efcf065fb8 100644--- a/spec/models/report_spec.rb+++ b/spec/models/report_spec.rb@@ -46,6 +46,8 @@ RSpec.describe Report dodescribe "counting" dodescribe "requests" do+ subject(:json) { Report.find("http_total_reqs").as_json }+before dofreeze_time DateTime.parse("2017-03-01 12:00")@@ -89,8 +91,6 @@ RSpec.describe Report doApplicationRequest.insert_all(application_requests)end- subject(:json) { Report.find("http_total_reqs").as_json }-it "counts the correct records" doexpect(json[:data].size).to eq(31) # today and 30 full daysexpect(json[:data][0..-2].sum { |d| d[:y] }).to eq(300)diff --git a/spec/models/screened_email_spec.rb b/spec/models/screened_email_spec.rbindex 802b9aa83f1..479df6b19bb 100644--- a/spec/models/screened_email_spec.rb+++ b/spec/models/screened_email_spec.rb@@ -52,7 +52,7 @@ RSpec.describe ScreenedEmail doenddescribe "#should_block?" do- subject { ScreenedEmail.should_block?(email) }+ subject(:should_block) { ScreenedEmail.should_block?(email) }it "automatically blocks via email canonicalization" doSiteSetting.levenshtein_distance_spammer_emails = 0@@ -63,7 +63,7 @@ RSpec.describe ScreenedEmail doendit "returns false if a record with the email doesn't exist" do- expect(subject).to eq(false)+ expect(should_block).to eq(false)endit "returns true when there is a record with the email" do@@ -86,7 +86,7 @@ RSpec.describe ScreenedEmail doshared_examples "when a ScreenedEmail record matches" doit "updates statistics" dofreeze_time do- expect { subject }.to change { screened_email.reload.match_count }.by(1)+ expect { should_block }.to change { screened_email.reload.match_count }.by(1)expect(screened_email.last_match_at).to eq_time(Time.zone.now)endenddiff --git a/spec/models/screened_url_spec.rb b/spec/models/screened_url_spec.rbindex cfcc685ec50..a6ad06cdb2b 100644--- a/spec/models/screened_url_spec.rb+++ b/spec/models/screened_url_spec.rb@@ -25,27 +25,28 @@ RSpec.describe ScreenedUrl doenddescribe "normalize" do- let(:record) { described_class.new(@params) }- subject do+ subject(:normalized) dorecord.normalizerecordend+ let(:record) { described_class.new(@params) }+%w[http:// HTTP:// https:// HTTPS://].each do |prefix|it "strips #{prefix}" do@params = valid_params.merge(url: url.gsub("http://", prefix))- expect(subject.url).to eq(url.gsub("http://", ""))+ expect(normalized.url).to eq(url.gsub("http://", ""))endendit "strips trailing slash" do@params = valid_params.merge(url: "silverbullet.in/")- expect(subject.url).to eq("silverbullet.in")+ expect(normalized.url).to eq("silverbullet.in")endit "strips trailing slashes" do@params = valid_params.merge(url: "silverbullet.in/buy///")- expect(subject.url).to eq("silverbullet.in/buy")+ expect(normalized.url).to eq("silverbullet.in/buy")endit "downcases domains" dodiff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rbindex 47e6b886cb6..9791733edc9 100644--- a/spec/models/tag_spec.rb+++ b/spec/models/tag_spec.rb@@ -35,13 +35,13 @@ RSpec.describe Tag doenddescribe "new" do- subject { Fabricate.build(:tag) }+ subject(:tag) { Fabricate.build(:tag) }it "triggers a extensibility event" do- event = DiscourseEvent.track_events { subject.save! }.last+ event = DiscourseEvent.track_events { tag.save! }.lastexpect(event[:event_name]).to eq(:tag_created)- expect(event[:params].first).to eq(subject)+ expect(event[:params].first).to eq(tag)endit "prevents case-insensitive duplicates" do@@ -59,13 +59,13 @@ RSpec.describe Tag doenddescribe "destroy" do- subject { Fabricate(:tag) }+ subject(:tag) { Fabricate(:tag) }it "triggers a extensibility event" do- event = DiscourseEvent.track_events { subject.destroy! }.last+ event = DiscourseEvent.track_events { tag.destroy! }.lastexpect(event[:event_name]).to eq(:tag_destroyed)- expect(event[:params].first).to eq(subject)+ expect(event[:params].first).to eq(tag)endit "removes it from its tag group" dodiff --git a/spec/models/trust_level3_requirements_spec.rb b/spec/models/trust_level3_requirements_spec.rbindex 19bc70b132c..d5abacef6fc 100644--- a/spec/models/trust_level3_requirements_spec.rb+++ b/spec/models/trust_level3_requirements_spec.rb@@ -1,10 +1,10 @@# frozen_string_literal: trueRSpec.describe TrustLevel3Requirements do- fab!(:user) { Fabricate(:user) }subject(:tl3_requirements) { described_class.new(user) }- fab!(:moderator) { Fabricate(:moderator) }+ fab!(:user) { Fabricate(:user) }+ fab!(:moderator) { Fabricate(:moderator) }fab!(:topic1) { Fabricate(:topic) }fab!(:topic2) { Fabricate(:topic) }fab!(:topic3) { Fabricate(:topic) }diff --git a/spec/models/user_field_spec.rb b/spec/models/user_field_spec.rbindex f39d3911a29..cf056e5f0b0 100644--- a/spec/models/user_field_spec.rb+++ b/spec/models/user_field_spec.rb@@ -2,12 +2,14 @@RSpec.describe UserField dodescribe "doesn't validate presence of name if field type is 'confirm'" do- subject { described_class.new(field_type: "confirm") }+ subject(:confirm_field) { described_class.new(field_type: "confirm") }+it { is_expected.not_to validate_presence_of :name }enddescribe "validates presence of name for other field types" do- subject { described_class.new(field_type: "dropdown") }+ subject(:dropdown_field) { described_class.new(field_type: "dropdown") }+it { is_expected.to validate_presence_of :name }enddiff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rbindex 892fafc04fd..1c5ecc381d9 100644--- a/spec/models/user_spec.rb+++ b/spec/models/user_spec.rb@@ -641,35 +641,33 @@ RSpec.describe User doenddescribe "new" do- subject { Fabricate.build(:user) }+ subject(:user) { Fabricate.build(:user) }it { is_expected.to be_valid }it { is_expected.not_to be_admin }it { is_expected.not_to be_approved }it "is properly initialized" do- expect(subject.approved_at).to be_blank- expect(subject.approved_by_id).to be_blank+ expect(user.approved_at).to be_blank+ expect(user.approved_by_id).to be_blankendit "triggers an extensibility event" do- event = DiscourseEvent.track_events { subject.save! }.first+ event = DiscourseEvent.track_events { user.save! }.firstexpect(event[:event_name]).to eq(:user_created)- expect(event[:params].first).to eq(subject)+ expect(event[:params].first).to eq(user)endcontext "with after_save" do- before { subject.save! }+ before { user.save! }it "has correct settings" do- expect(subject.email_tokens).to be_present- expect(subject.user_stat).to be_present- expect(subject.user_profile).to be_present- expect(subject.user_option.email_messages_level).to eq(- UserOption.email_level_types[:always],- )- expect(subject.user_option.email_level).to eq(UserOption.email_level_types[:only_when_away])+ expect(user.email_tokens).to be_present+ expect(user.user_stat).to be_present+ expect(user.user_profile).to be_present+ expect(user.user_option.email_messages_level).to eq(UserOption.email_level_types[:always])+ expect(user.user_option.email_level).to eq(UserOption.email_level_types[:only_when_away])endend@@ -756,41 +754,37 @@ RSpec.describe User doenddescribe "staff and regular users" do- let(:user) { Fabricate.build(:user) }+ subject(:user) { Fabricate.build(:user) }describe "#staff?" do- subject { user.staff? }-- it { is_expected.to eq(false) }+ it { is_expected.not_to be_staff }context "for a moderator user" dobefore { user.moderator = true }- it { is_expected.to eq(true) }+ it { is_expected.to be_staff }endcontext "for an admin user" dobefore { user.admin = true }- it { is_expected.to eq(true) }+ it { is_expected.to be_staff }endenddescribe "#regular?" do- subject { user.regular? }-- it { is_expected.to eq(true) }+ it { is_expected.to be_regular }context "for a moderator user" dobefore { user.moderator = true }- it { is_expected.to eq(false) }+ it { is_expected.not_to be_regular }endcontext "for an admin user" dobefore { user.admin = true }- it { is_expected.to eq(false) }+ it { is_expected.not_to be_regular }endendend@@ -3251,7 +3245,7 @@ RSpec.describe User doendit "returns false if no whispers groups exist" do- expect(subject.whisperer?).to eq(false)+ expect(user.whisperer?).to eq(false)endenddiff --git a/spec/models/web_hook_spec.rb b/spec/models/web_hook_spec.rbindex 8a3fbef6efb..5a6bf1757ab 100644--- a/spec/models/web_hook_spec.rb+++ b/spec/models/web_hook_spec.rb@@ -7,30 +7,30 @@ RSpec.describe WebHook doit { is_expected.to validate_presence_of :web_hook_event_types }describe "#content_types" do- subject { WebHook.content_types }+ subject(:content_types) { WebHook.content_types }it "'json' (application/json) should be at 1st position" do- expect(subject["application/json"]).to eq(1)+ expect(content_types["application/json"]).to eq(1)endit "'url_encoded' (application/x-www-form-urlencoded) should be at 2st position" do- expect(subject["application/x-www-form-urlencoded"]).to eq(2)+ expect(content_types["application/x-www-form-urlencoded"]).to eq(2)endenddescribe "#last_delivery_statuses" do- subject { WebHook.last_delivery_statuses }+ subject(:statuses) { WebHook.last_delivery_statuses }it "inactive should be at 1st position" do- expect(subject[:inactive]).to eq(1)+ expect(statuses[:inactive]).to eq(1)endit "failed should be at 2st position" do- expect(subject[:failed]).to eq(2)+ expect(statuses[:failed]).to eq(2)endit "successful should be at 3st position" do- expect(subject[:successful]).to eq(3)+ expect(statuses[:successful]).to eq(3)endenddiff --git a/spec/requests/tags_controller_spec.rb b/spec/requests/tags_controller_spec.rbindex 4e7ffe6ad18..238e6cae103 100644--- a/spec/requests/tags_controller_spec.rb+++ b/spec/requests/tags_controller_spec.rb@@ -1347,18 +1347,19 @@ RSpec.describe TagsController doenddescribe "#destroy_synonym" do+ subject(:destroy_synonym) { delete("/tag/#{tag.name}/synonyms/#{synonym.name}.json") }+fab!(:tag) { Fabricate(:tag) }fab!(:synonym) { Fabricate(:tag, target_tag: tag, name: "synonym") }- subject { delete("/tag/#{tag.name}/synonyms/#{synonym.name}.json") }it "fails if not logged in" do- subject+ destroy_synonymexpect(response.status).to eq(403)endit "fails if not staff user" dosign_in(user)- subject+ destroy_synonymexpect(response.status).to eq(403)end@@ -1367,7 +1368,7 @@ RSpec.describe TagsController doit "can remove a synonym from a tag" dosynonym2 = Fabricate(:tag, target_tag: tag, name: "synonym2")- expect { subject }.to_not change { Tag.count }+ expect { destroy_synonym }.to_not change { Tag.count }expect_same_tag_names(tag.reload.synonyms, [synonym2])expect(synonym.reload).to_not be_synonymenddiff --git a/spec/serializers/admin_plugin_serializer_spec.rb b/spec/serializers/admin_plugin_serializer_spec.rbindex 6e242356606..eb2a86bc828 100644--- a/spec/serializers/admin_plugin_serializer_spec.rb+++ b/spec/serializers/admin_plugin_serializer_spec.rb@@ -1,14 +1,14 @@# frozen_string_literal: trueRSpec.describe AdminPluginSerializer do- let(:instance) { Plugin::Instance.new }+ subject(:serializer) { described_class.new(instance) }- subject { described_class.new(instance) }+ let(:instance) { Plugin::Instance.new }describe "enabled_setting" doit "should return the right value" doinstance.enabled_site_setting("test")- expect(subject.enabled_setting).to eq("test")+ expect(serializer.enabled_setting).to eq("test")endenddiff --git a/spec/serializers/basic_group_serializer_spec.rb b/spec/serializers/basic_group_serializer_spec.rbindex 7758fda3ce7..c4800008f52 100644--- a/spec/serializers/basic_group_serializer_spec.rb+++ b/spec/serializers/basic_group_serializer_spec.rb@@ -1,16 +1,17 @@# frozen_string_literal: trueRSpec.describe BasicGroupSerializer do+ subject(:serializer) { described_class.new(group, scope: guardian, root: false) }+let(:guardian) { Guardian.new }fab!(:group) { Fabricate(:group) }- subject { described_class.new(group, scope: guardian, root: false) }describe "#display_name" dodescribe "automatic group" dolet(:group) { Group.find(1) }it "should include the display name" do- expect(subject.display_name).to eq(I18n.t("groups.default_names.admins"))+ expect(serializer.display_name).to eq(I18n.t("groups.default_names.admins"))endend@@ -18,22 +19,22 @@ RSpec.describe BasicGroupSerializer dofab!(:group) { Fabricate(:group) }it "should not include the display name" do- expect(subject.display_name).to eq(nil)+ expect(serializer.display_name).to eq(nil)endendenddescribe "#bio_raw" do- fab!(:group) { Fabricate(:group, bio_raw: "testing :slightly_smiling_face:") }-- subject do+ subject(:serializer) dodescribed_class.new(group, scope: guardian, root: false, owner_group_ids: [group.id])end+ fab!(:group) { Fabricate(:group, bio_raw: "testing :slightly_smiling_face:") }+describe "group owner" doit "should include bio_raw" do- expect(subject.as_json[:bio_raw]).to eq("testing :slightly_smiling_face:")- expect(subject.as_json[:bio_excerpt]).to start_with("testing <img")+ expect(serializer.as_json[:bio_raw]).to eq("testing :slightly_smiling_face:")+ expect(serializer.as_json[:bio_excerpt]).to start_with("testing <img")endendend@@ -48,7 +49,7 @@ RSpec.describe BasicGroupSerializer doit "should be present" doGroup.refresh_automatic_groups!- expect(subject.as_json[:has_messages]).to eq(true)+ expect(serializer.as_json[:has_messages]).to eq(true)endend@@ -59,7 +60,7 @@ RSpec.describe BasicGroupSerializer dobefore { group.add(user) }it "should be present" do- expect(subject.as_json[:has_messages]).to eq(true)+ expect(serializer.as_json[:has_messages]).to eq(true)endend@@ -67,7 +68,7 @@ RSpec.describe BasicGroupSerializer dolet(:guardian) { Guardian.new(Fabricate(:user)) }it "should not be present" do- expect(subject.as_json[:has_messages]).to eq(nil)+ expect(serializer.as_json[:has_messages]).to eq(nil)endendend@@ -82,7 +83,7 @@ RSpec.describe BasicGroupSerializer dobefore { group.add(user) }it "should be true" do- expect(subject.as_json[:can_see_members]).to eq(true)+ expect(serializer.as_json[:can_see_members]).to eq(true)endend@@ -90,7 +91,7 @@ RSpec.describe BasicGroupSerializer dolet(:guardian) { Guardian.new(Fabricate(:user)) }it "should be false" do- expect(subject.as_json[:can_see_members]).to eq(false)+ expect(serializer.as_json[:can_see_members]).to eq(false)endendenddiff --git a/spec/serializers/basic_reviewable_flagged_post_serializer_spec.rb b/spec/serializers/basic_reviewable_flagged_post_serializer_spec.rbindex 3e8dfe9ae17..e5ef2c87ff6 100644--- a/spec/serializers/basic_reviewable_flagged_post_serializer_spec.rb+++ b/spec/serializers/basic_reviewable_flagged_post_serializer_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: truedescribe BasicReviewableFlaggedPostSerializer do+ subject(:serializer) { described_class.new(reviewable, root: false).as_json }+fab!(:topic) { Fabricate(:topic, title: "safe title <a> hello world") }fab!(:post) { Fabricate(:post, topic: topic) }@@ -12,29 +14,27 @@ describe BasicReviewableFlaggedPostSerializer do)end- subject { described_class.new(reviewable, root: false).as_json }-include_examples "basic reviewable attributes"describe "#post_number" doit "equals the post_number of the post" do- expect(subject[:post_number]).to eq(post.post_number)+ expect(serializer[:post_number]).to eq(post.post_number)endit "is not included if the reviewable is associated with no post" doreviewable.update!(target: nil)- expect(subject.key?(:post_number)).to eq(false)+ expect(serializer.key?(:post_number)).to eq(false)endenddescribe "#topic_fancy_title" doit "equals the fancy_title of the topic" do- expect(subject[:topic_fancy_title]).to eq("Safe title <a> hello world")+ expect(serializer[:topic_fancy_title]).to eq("Safe title <a> hello world")endit "is not included if the reviewable is associated with no topic" doreviewable.update!(topic: nil)- expect(subject.key?(:topic_fancy_title)).to eq(false)+ expect(serializer.key?(:topic_fancy_title)).to eq(false)endendenddiff --git a/spec/serializers/basic_reviewable_queued_post_serializer_spec.rb b/spec/serializers/basic_reviewable_queued_post_serializer_spec.rbindex eb332dc8db8..6cb0728a8e3 100644--- a/spec/serializers/basic_reviewable_queued_post_serializer_spec.rb+++ b/spec/serializers/basic_reviewable_queued_post_serializer_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: truedescribe BasicReviewableQueuedPostSerializer do+ subject(:serializer) { described_class.new(reviewable, root: false).as_json }+fab!(:topic) { Fabricate(:topic, title: "safe title <a> existing topic") }fab!(:reviewable) doReviewableQueuedPost.create!(@@ -13,40 +15,38 @@ describe BasicReviewableQueuedPostSerializer do)end- subject { described_class.new(reviewable, root: false).as_json }-include_examples "basic reviewable attributes"describe "#topic_fancy_title" doit "equals the topic's fancy_title" do- expect(subject[:topic_fancy_title]).to eq("Safe title <a> existing topic")+ expect(serializer[:topic_fancy_title]).to eq("Safe title <a> existing topic")endit "is not included if the reviewable is associated with no topic" doreviewable.update!(topic: nil)- expect(subject.key?(:topic_fancy_title)).to eq(false)+ expect(serializer.key?(:topic_fancy_title)).to eq(false)endenddescribe "#is_new_topic" doit "is true if the reviewable's payload has a title attribute" do- expect(subject[:is_new_topic]).to eq(true)+ expect(serializer[:is_new_topic]).to eq(true)endit "is false if the reviewable's payload doesn't have a title attribute" doreviewable.update!(payload: { raw: "new post 123" })- expect(subject[:is_new_topic]).to eq(false)+ expect(serializer[:is_new_topic]).to eq(false)endenddescribe "#payload_title" doit "equals the title in the reviewable's payload" do- expect(subject[:payload_title]).to eq("unsafe title <a>")+ expect(serializer[:payload_title]).to eq("unsafe title <a>")endit "is not included if the reviewable's payload doesn't have a title attribute" doreviewable.update!(payload: { raw: "new post 123" })- expect(subject.key?(:payload_title)).to eq(false)+ expect(serializer.key?(:payload_title)).to eq(false)endendenddiff --git a/spec/serializers/basic_reviewable_user_serializer_spec.rb b/spec/serializers/basic_reviewable_user_serializer_spec.rbindex abf8f6f9106..f16f899b2cd 100644--- a/spec/serializers/basic_reviewable_user_serializer_spec.rb+++ b/spec/serializers/basic_reviewable_user_serializer_spec.rb@@ -1,8 +1,9 @@# frozen_string_literal: truedescribe BasicReviewableUserSerializer do- fab!(:user) { Fabricate(:user) }+ subject(:serializer) { described_class.new(reviewable, root: false).as_json }+ fab!(:user) { Fabricate(:user) }fab!(:reviewable) doReviewableUser.needs_review!(target: user,@@ -17,13 +18,11 @@ describe BasicReviewableUserSerializer do)end- subject { described_class.new(reviewable, root: false).as_json }-include_examples "basic reviewable attributes"describe "#username" doit "equals the username in the reviewable's payload" do- expect(subject[:username]).to eq(user.username)+ expect(serializer[:username]).to eq(user.username)endendenddiff --git a/spec/serializers/category_upload_serializer_spec.rb b/spec/serializers/category_upload_serializer_spec.rbindex c46b2ad501c..eef9d1f9528 100644--- a/spec/serializers/category_upload_serializer_spec.rb+++ b/spec/serializers/category_upload_serializer_spec.rb@@ -1,11 +1,12 @@# frozen_string_literal: trueRSpec.describe CategoryUploadSerializer do+ subject(:serializer) { described_class.new(upload, root: false) }+fab!(:upload) { Fabricate(:upload) }- let(:subject) { described_class.new(upload, root: false) }it "should include width and height" do- expect(subject.width).to eq(upload.width)- expect(subject.height).to eq(upload.height)+ expect(serializer.width).to eq(upload.width)+ expect(serializer.height).to eq(upload.height)endenddiff --git a/spec/serializers/emoji_serializer_spec.rb b/spec/serializers/emoji_serializer_spec.rbindex 732e78da1b1..8c9487f542a 100644--- a/spec/serializers/emoji_serializer_spec.rb+++ b/spec/serializers/emoji_serializer_spec.rb@@ -4,16 +4,17 @@ RSpec.describe EmojiSerializer dofab!(:custom_emoji) { CustomEmoji.create!(name: "trout", upload: Fabricate(:upload)) }describe "#url" do+ subject(:serializer) { described_class.new(emoji, root: false) }+fab!(:emoji) { Emoji.load_custom.first }- subject { described_class.new(emoji, root: false) }it "returns a valid URL" do- expect(subject.url).to start_with("/uploads/")+ expect(serializer.url).to start_with("/uploads/")endit "works with a CDN" doset_cdn_url("https://cdn.com")- expect(subject.url).to start_with("https://cdn.com")+ expect(serializer.url).to start_with("https://cdn.com")endenddiff --git a/spec/serializers/group_show_serializer_spec.rb b/spec/serializers/group_show_serializer_spec.rbindex b69d37ef5a4..2bd872d0aa5 100644--- a/spec/serializers/group_show_serializer_spec.rb+++ b/spec/serializers/group_show_serializer_spec.rb@@ -59,15 +59,16 @@ RSpec.describe GroupShowSerializer doenddescribe "admin only fields" do+ subject(:serializer) { described_class.new(group, scope: guardian, root: false) }+fab!(:group) { Fabricate(:group, email_username: "[email protected]", email_password: "pa$$w0rd") }- subject { described_class.new(group, scope: guardian, root: false) }context "for a user" dolet(:guardian) { Guardian.new(Fabricate(:user)) }it "are not visible" do- expect(subject.as_json[:email_username]).to be_nil- expect(subject.as_json[:email_password]).to be_nil+ expect(serializer.as_json[:email_username]).to be_nil+ expect(serializer.as_json[:email_password]).to be_nilendend@@ -75,15 +76,16 @@ RSpec.describe GroupShowSerializer dolet(:guardian) { Guardian.new(Fabricate(:admin)) }it "are visible" do- expect(subject.as_json[:email_username]).to eq("[email protected]")- expect(subject.as_json[:email_password]).to eq("pa$$w0rd")- expect(subject.as_json[:message_count]).to eq(0)+ expect(serializer.as_json[:email_username]).to eq("[email protected]")+ expect(serializer.as_json[:email_password]).to eq("pa$$w0rd")+ expect(serializer.as_json[:message_count]).to eq(0)endendenddescribe "default notification settings" do- subject { described_class.new(group, scope: guardian, root: false) }+ subject(:serializer) { described_class.new(group, scope: guardian, root: false) }+let(:category1) { Fabricate(:category) }let(:category2) { Fabricate(:category) }let(:tag1) { Fabricate(:tag) }@@ -118,8 +120,10 @@ RSpec.describe GroupShowSerializer dolet(:guardian) { Guardian.new(Fabricate(:user)) }it "are not visible" do- expect(subject.as_json.keys.select { |k| k.to_s.ends_with?("_category_ids") }).to be_empty- expect(subject.as_json.keys.select { |k| k.to_s.ends_with?("_tags") }).to be_empty+ expect(+ serializer.as_json.keys.select { |k| k.to_s.ends_with?("_category_ids") },+ ).to be_empty+ expect(serializer.as_json.keys.select { |k| k.to_s.ends_with?("_tags") }).to be_emptyendend@@ -127,25 +131,25 @@ RSpec.describe GroupShowSerializer dolet(:guardian) { Guardian.new(Fabricate(:admin)) }it "are correct" do- expect(subject.as_json[:watching_category_ids]).to eq([category1.id])- expect(subject.as_json[:tracking_category_ids]).to eq([category2.id])- expect(subject.as_json[:watching_first_post_category_ids]).to eq([])- expect(subject.as_json[:regular_category_ids]).to eq([])- expect(subject.as_json[:muted_category_ids]).to eq([])-- expect(subject.as_json[:watching_tags]).to eq([tag1.name])- expect(subject.as_json[:tracking_tags]).to eq([tag2.name])- expect(subject.as_json[:watching_first_post_tags]).to eq([])- expect(subject.as_json[:regular_tags]).to eq([])- expect(subject.as_json[:muted_tags]).to eq([])+ expect(serializer.as_json[:watching_category_ids]).to eq([category1.id])+ expect(serializer.as_json[:tracking_category_ids]).to eq([category2.id])+ expect(serializer.as_json[:watching_first_post_category_ids]).to eq([])+ expect(serializer.as_json[:regular_category_ids]).to eq([])+ expect(serializer.as_json[:muted_category_ids]).to eq([])++ expect(serializer.as_json[:watching_tags]).to eq([tag1.name])+ expect(serializer.as_json[:tracking_tags]).to eq([tag2.name])+ expect(serializer.as_json[:watching_first_post_tags]).to eq([])+ expect(serializer.as_json[:regular_tags]).to eq([])+ expect(serializer.as_json[:muted_tags]).to eq([])endit "doesn't include tag fields if tags are disabled" doSiteSetting.tagging_enabled = false- expect(subject.as_json.keys.select { |k| k.to_s.ends_with?("_category_ids") }.length).to eq(- 5,- )- expect(subject.as_json.keys.select { |k| k.to_s.ends_with?("_tags") }).to be_empty+ expect(+ serializer.as_json.keys.select { |k| k.to_s.ends_with?("_category_ids") }.length,+ ).to eq(5)+ expect(serializer.as_json.keys.select { |k| k.to_s.ends_with?("_tags") }).to be_emptyendendenddiff --git a/spec/serializers/post_serializer_spec.rb b/spec/serializers/post_serializer_spec.rbindex 39d7cbe6c75..0b728696c83 100644--- a/spec/serializers/post_serializer_spec.rb+++ b/spec/serializers/post_serializer_spec.rb@@ -68,35 +68,35 @@ RSpec.describe PostSerializer doendcontext "with a post by a nuked user" do- before { post.update!(user_id: nil, deleted_at: Time.zone.now) }-- subject do+ subject(:serializer) doPostSerializer.new(post, scope: Guardian.new(Fabricate(:admin)), root: false).as_jsonend+ before { post.update!(user_id: nil, deleted_at: Time.zone.now) }+it "serializes correctly" do%i[name username display_username avatar_template user_title trust_level].each do |attr|- expect(subject[attr]).to be_nil+ expect(serializer[attr]).to be_nilend- %i[moderator staff yours].each { |attr| expect(subject[attr]).to eq(false) }+ %i[moderator staff yours].each { |attr| expect(serializer[attr]).to eq(false) }endendcontext "with a post by a suspended user" do- def subject+ def serializerPostSerializer.new(post, scope: Guardian.new(Fabricate(:admin)), root: false).as_jsonendit "serializes correctly" do- expect(subject[:user_suspended]).to be_nil+ expect(serializer[:user_suspended]).to be_nilpost.user.update!(suspended_till: 1.month.from_now)- expect(subject[:user_suspended]).to eq(true)+ expect(serializer[:user_suspended]).to eq(true)freeze_time (2.months.from_now)- expect(subject[:user_suspended]).to be_nil+ expect(serializer[:user_suspended]).to be_nilendenddiff --git a/spec/serializers/suggested_topic_serializer_spec.rb b/spec/serializers/suggested_topic_serializer_spec.rbindex 4627f95c6b0..0d777dc189e 100644--- a/spec/serializers/suggested_topic_serializer_spec.rb+++ b/spec/serializers/suggested_topic_serializer_spec.rb@@ -5,6 +5,10 @@ RSpec.describe SuggestedTopicSerializer dolet(:admin) { Fabricate(:admin) }describe "#featured_link and #featured_link_root_domain" do+ subject(:json) do+ SuggestedTopicSerializer.new(topic, scope: Guardian.new(user), root: false).as_json+ end+let(:featured_link) { "http://meta.discourse.org" }let(:topic) doFabricate(@@ -13,9 +17,6 @@ RSpec.describe SuggestedTopicSerializer docategory: Fabricate(:category, topic_featured_link_allowed: true),)end- subject(:json) do- SuggestedTopicSerializer.new(topic, scope: Guardian.new(user), root: false).as_json- endcontext "when topic featured link is disable" dobefore dodiff --git a/spec/serializers/upload_serializer_spec.rb b/spec/serializers/upload_serializer_spec.rbindex b2734c38822..39c4b6ded49 100644--- a/spec/serializers/upload_serializer_spec.rb+++ b/spec/serializers/upload_serializer_spec.rb@@ -1,11 +1,12 @@# frozen_string_literal: trueRSpec.describe UploadSerializer do+ subject(:serializer) { UploadSerializer.new(upload, root: false) }+fab!(:upload) { Fabricate(:upload) }- let(:subject) { UploadSerializer.new(upload, root: false) }it "should render without errors" do- json_data = JSON.parse(subject.to_json)+ json_data = JSON.parse(serializer.to_json)expect(json_data["id"]).to eql upload.idexpect(json_data["width"]).to eql upload.width@@ -21,7 +22,7 @@ RSpec.describe UploadSerializer docontext "when secure uploads is disabled" doit "just returns the normal URL, otherwise S3 errors are encountered" doUrlHelper.expects(:cook_url).with(upload.url, secure: false)- subject.to_json+ serializer.to_jsonendend@@ -33,7 +34,7 @@ RSpec.describe UploadSerializer doit "returns the cooked URL based on the upload URL" doUrlHelper.expects(:cook_url).with(upload.url, secure: true)- subject.to_json+ serializer.to_jsonendendenddiff --git a/spec/services/auto_silence_spec.rb b/spec/services/auto_silence_spec.rbindex cfdac5eb0d8..669d4e5701b 100644--- a/spec/services/auto_silence_spec.rb+++ b/spec/services/auto_silence_spec.rb@@ -9,12 +9,13 @@ RSpec.describe SpamRule::AutoSilence doenddescribe "perform" do+ subject(:autosilence) { described_class.new(post.user) }+let(:user) { Fabricate.build(:newuser) }let(:post) { Fabricate(:post, user: user) }- subject { described_class.new(post.user) }it "takes no action if user should not be silenced" do- subject.perform+ autosilence.performexpect(post.user.reload).not_to be_silencedend@@ -23,81 +24,84 @@ RSpec.describe SpamRule::AutoSilence doSiteSetting.silence_new_user_sensitivity = Reviewable.sensitivities[:low]SiteSetting.num_users_to_silence_new_user = 1PostActionCreator.spam(Discourse.system_user, post)- subject.perform+ autosilence.performexpect(post.user.reload).to be_silencedendenddescribe "total_spam_score" do+ subject(:score) { enforcer.user_spam_stats.total_spam_score }+let(:post) { Fabricate(:post) }let(:enforcer) { described_class.new(post.user) }let(:flagger) { Fabricate(:user) }- subject { enforcer.user_spam_stats.total_spam_score }it "returns 0 when there are no flags" do- expect(subject).to eq(0)+ expect(score).to eq(0)endit "returns 0 when there is one flag that has a reason other than spam" doPostActionCreator.off_topic(flagger, post)- expect(subject).to eq(0)+ expect(score).to eq(0)endit "returns the score when there are two flags with spam as the reason" doPostActionCreator.spam(Fabricate(:user), post)PostActionCreator.spam(Fabricate(:user), post)- expect(subject).to eq(4.0)+ expect(score).to eq(4.0)endit "returns the score when there are two spam flags, each on a different post" doPostActionCreator.spam(Fabricate(:user), post)PostActionCreator.spam(Fabricate(:user), Fabricate(:post, user: post.user))- expect(subject).to eq(4.0)+ expect(score).to eq(4.0)endenddescribe "spam_user_count" do+ subject(:count) { enforcer.user_spam_stats.spam_user_count }+let(:post) { Fabricate(:post) }let(:enforcer) { described_class.new(post.user) }- subject { enforcer.user_spam_stats.spam_user_count }it "returns 0 when there are no flags" do- expect(subject).to eq(0)+ expect(count).to eq(0)endit "returns 0 when there is one flag that has a reason other than spam" doFabricate(:flag, post: post, post_action_type_id: PostActionType.types[:off_topic])- expect(subject).to eq(0)+ expect(count).to eq(0)endit "returns 1 when there is one spam flag" doPostActionCreator.spam(Fabricate(:user), post)- expect(subject).to eq(1)+ expect(count).to eq(1)endit "returns 2 when there are two spam flags from 2 users" doPostActionCreator.spam(Fabricate(:user), post)PostActionCreator.spam(Fabricate(:user), post)- expect(subject).to eq(2)+ expect(count).to eq(2)endit "returns 1 when there are two spam flags on two different posts from 1 user" doflagger = Fabricate(:user)PostActionCreator.spam(flagger, post)PostActionCreator.spam(flagger, Fabricate(:post, user: post.user))- expect(subject).to eq(1)+ expect(count).to eq(1)endenddescribe "#silence_user" do+ subject(:autosilence) { described_class.new(user) }+let!(:admin) { Fabricate(:admin) } # needed for SystemMessagelet(:user) { Fabricate(:user) }let!(:post) { Fabricate(:post, user: user) }- subject { described_class.new(user) }context "when user is not silenced" doit "prevents the user from making new posts" do- subject.silence_user+ autosilence.silence_userexpect(user).to be_silencedexpect(Guardian.new(user).can_create_post?(nil)).to be_falseyend@@ -107,14 +111,14 @@ RSpec.describe SpamRule::AutoSilence doit "sends private message to moderators" doSiteSetting.notify_mods_when_user_silenced = true- subject.silence_user- expect(subject.group_message).to be_present+ autosilence.silence_user+ expect(autosilence.group_message).to be_presentendit "doesn't send a pm to moderators if notify_mods_when_user_silenced is false" doSiteSetting.notify_mods_when_user_silenced = false- subject.silence_user- expect(subject.group_message).to be_blank+ autosilence.silence_user+ expect(autosilence.group_message).to be_blankendendend@@ -123,8 +127,8 @@ RSpec.describe SpamRule::AutoSilence dobefore { UserSilencer.silence(user) }it "doesn't send a pm to moderators if the user is already silenced" do- subject.silence_user- expect(subject.group_message).to be_blank+ autosilence.silence_user+ expect(autosilence.group_message).to be_blankendendend@@ -167,20 +171,21 @@ RSpec.describe SpamRule::AutoSilence doendcontext "with new user" do- subject { described_class.new(user) }- let(:stats) { subject.user_spam_stats }+ subject(:autosilence) { described_class.new(user) }++ let(:stats) { autosilence.user_spam_stats }it "returns false if there are no spam flags" doexpect(stats.total_spam_score).to eq(0)expect(stats.spam_user_count).to eq(0)- expect(subject.should_autosilence?).to eq(false)+ expect(autosilence.should_autosilence?).to eq(false)endit "returns false if there are not received enough flags" doPostActionCreator.spam(flagger, post)expect(stats.total_spam_score).to eq(2.0)expect(stats.spam_user_count).to eq(1)- expect(subject.should_autosilence?).to eq(false)+ expect(autosilence.should_autosilence?).to eq(false)endit "returns false if there have not been enough users" do@@ -188,21 +193,21 @@ RSpec.describe SpamRule::AutoSilence doPostActionCreator.spam(flagger, post2)expect(stats.total_spam_score).to eq(4.0)expect(stats.spam_user_count).to eq(1)- expect(subject.should_autosilence?).to eq(false)+ expect(autosilence.should_autosilence?).to eq(false)endit "returns false if silence_new_user_sensitivity is disabled" doSiteSetting.silence_new_user_sensitivity = Reviewable.sensitivities[:disabled]PostActionCreator.spam(flagger, post)PostActionCreator.spam(flagger2, post)- expect(subject.should_autosilence?).to eq(false)+ expect(autosilence.should_autosilence?).to eq(false)endit "returns false if num_users_to_silence_new_user is 0" doSiteSetting.num_users_to_silence_new_user = 0PostActionCreator.spam(flagger, post)PostActionCreator.spam(flagger2, post)- expect(subject.should_autosilence?).to eq(false)+ expect(autosilence.should_autosilence?).to eq(false)endit "returns true when there are enough flags from enough users" do@@ -210,16 +215,17 @@ RSpec.describe SpamRule::AutoSilence doPostActionCreator.spam(flagger2, post)expect(stats.total_spam_score).to eq(4.0)expect(stats.spam_user_count).to eq(2)- expect(subject.should_autosilence?).to eq(true)+ expect(autosilence.should_autosilence?).to eq(true)endendcontext "when silenced, but has higher trust level now" do+ subject(:autosilence) { described_class.new(user) }+let(:user) { Fabricate(:user, silenced_till: 1.year.from_now, trust_level: TrustLevel[1]) }- subject { described_class.new(user) }it "returns false" do- expect(subject.should_autosilence?).to eq(false)+ expect(autosilence.should_autosilence?).to eq(false)endendenddiff --git a/spec/services/email_settings_exception_handler_spec.rb b/spec/services/email_settings_exception_handler_spec.rbindex e70614dd608..1baa084abbc 100644--- a/spec/services/email_settings_exception_handler_spec.rb+++ b/spec/services/email_settings_exception_handler_spec.rb@@ -4,21 +4,21 @@ RSpec.describe EmailSettingsExceptionHandler dodescribe "#friendly_exception_message" doit "formats a Net::POPAuthenticationError" doexception = Net::POPAuthenticationError.new("invalid credentials")- expect(subject.class.friendly_exception_message(exception, "pop.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "pop.test.com")).to eq(I18n.t("email_settings.pop3_authentication_error"),)endit "formats a Net::IMAP::NoResponseError for invalid credentials" doexception = Net::IMAP::NoResponseError.new(stub(data: stub(text: "Invalid credentials")))- expect(subject.class.friendly_exception_message(exception, "imap.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "imap.test.com")).to eq(I18n.t("email_settings.imap_authentication_error"),)endit "formats a general Net::IMAP::NoResponseError" doexception = Net::IMAP::NoResponseError.new(stub(data: stub(text: "NO bad problem (Failure)")))- expect(subject.class.friendly_exception_message(exception, "imap.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "imap.test.com")).to eq(I18n.t("email_settings.imap_no_response_error", message: "NO bad problem"),)end@@ -28,14 +28,14 @@ RSpec.describe EmailSettingsExceptionHandler doNet::IMAP::NoResponseError.new(stub(data: stub(text: "NO Application-specific password required")),)- expect(subject.class.friendly_exception_message(exception, "imap.gmail.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "imap.gmail.com")).to eq(I18n.t("email_settings.authentication_error_gmail_app_password"),)endit "formats a Net::SMTPAuthenticationError" doexception = Net::SMTPAuthenticationError.new("invalid credentials")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.smtp_authentication_error"),)end@@ -43,58 +43,58 @@ RSpec.describe EmailSettingsExceptionHandler doit "formats a Net::SMTPAuthenticationError with application-specific password Gmail error" doexception =Net::SMTPAuthenticationError.new(nil, message: "Application-specific password required")- expect(subject.class.friendly_exception_message(exception, "smtp.gmail.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.gmail.com")).to eq(I18n.t("email_settings.authentication_error_gmail_app_password"),)endit "formats a Net::SMTPServerBusy" doexception = Net::SMTPServerBusy.new("call me maybe later")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.smtp_server_busy_error"),)endit "formats a Net::SMTPSyntaxError, Net::SMTPFatalError, and Net::SMTPUnknownError" doexception = Net::SMTPSyntaxError.new(nil, message: "bad syntax")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.smtp_unhandled_error", message: exception.message),)exception = Net::SMTPFatalError.new(nil, message: "fatal")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.smtp_unhandled_error", message: exception.message),)exception = Net::SMTPUnknownError.new(nil, message: "unknown")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.smtp_unhandled_error", message: exception.message),)endit "formats a SocketError and Errno::ECONNREFUSED" doexception = SocketError.new("bad socket")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.connection_error"),)exception = Errno::ECONNREFUSED.new("no thanks")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.connection_error"),)endit "formats a Net::OpenTimeout and Net::ReadTimeout error" doexception = Net::OpenTimeout.new("timed out")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.timeout_error"),)exception = Net::ReadTimeout.new("timed out")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.timeout_error"),)endit "formats unhandled errors" doexception = StandardError.new("unknown")- expect(subject.class.friendly_exception_message(exception, "smtp.test.com")).to eq(+ expect(described_class.friendly_exception_message(exception, "smtp.test.com")).to eq(I18n.t("email_settings.unhandled_error", message: exception.message),)enddiff --git a/spec/services/email_settings_validator_spec.rb b/spec/services/email_settings_validator_spec.rbindex 9ba5fb7e6e0..78bc11fcec0 100644--- a/spec/services/email_settings_validator_spec.rb+++ b/spec/services/email_settings_validator_spec.rb@@ -20,7 +20,12 @@ RSpec.describe EmailSettingsValidator donet_imap_stub.stubs(:logout).returns(true)net_imap_stub.stubs(:disconnect).returns(true)expect {- subject.class.validate_imap(host: host, port: port, username: username, password: password)+ described_class.validate_imap(+ host: host,+ port: port,+ username: username,+ password: password,+ )}.not_to raise_errorend@@ -30,7 +35,7 @@ RSpec.describe EmailSettingsValidator dostub(data: stub(text: "no response")),)expect {- subject.class.validate_imap(+ described_class.validate_imap(host: host,port: port,username: username,@@ -51,7 +56,7 @@ RSpec.describe EmailSettingsValidator do.with(regexp_matches(/\[EmailSettingsValidator\] Error encountered/)).at_least_onceexpect {- subject.class.validate_imap(+ described_class.validate_imap(host: host,port: port,username: username,@@ -77,14 +82,19 @@ RSpec.describe EmailSettingsValidator doit "is valid if no error is raised" doexpect {- subject.class.validate_pop3(host: host, port: port, username: username, password: password)+ described_class.validate_pop3(+ host: host,+ port: port,+ username: username,+ password: password,+ )}.not_to raise_errorendit "is invalid if an error is raised" donet_pop3_stub.stubs(:auth_only).raises(Net::POPAuthenticationError, "invalid credentials")expect {- subject.class.validate_pop3(+ described_class.validate_pop3(host: host,port: port,username: username,@@ -102,7 +112,7 @@ RSpec.describe EmailSettingsValidator do.at_least_oncenet_pop3_stub.stubs(:auth_only).raises(Net::POPAuthenticationError, "invalid credentials")expect {- subject.class.validate_pop3(+ described_class.validate_pop3(host: host,port: port,username: username,@@ -117,7 +127,12 @@ RSpec.describe EmailSettingsValidator doSiteSetting.pop3_polling_openssl_verify = truenet_pop3_stub.expects(:enable_ssl).with(max_version: OpenSSL::SSL::TLS1_2_VERSION)expect {- subject.class.validate_pop3(host: host, port: port, username: username, password: password)+ described_class.validate_pop3(+ host: host,+ port: port,+ username: username,+ password: password,+ )}.not_to raise_errorend@@ -126,7 +141,12 @@ RSpec.describe EmailSettingsValidator doSiteSetting.pop3_polling_openssl_verify = falsenet_pop3_stub.expects(:enable_ssl).with(OpenSSL::SSL::VERIFY_NONE)expect {- subject.class.validate_pop3(host: host, port: port, username: username, password: password)+ described_class.validate_pop3(+ host: host,+ port: port,+ username: username,+ password: password,+ )}.not_to raise_errorendend@@ -151,7 +171,7 @@ RSpec.describe EmailSettingsValidator doit "is valid if no error is raised" doexpect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,@@ -164,7 +184,7 @@ RSpec.describe EmailSettingsValidator doit "is invalid if an error is raised" donet_smtp_stub.stubs(:start).raises(Net::SMTPAuthenticationError, "invalid credentials")expect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,@@ -185,7 +205,7 @@ RSpec.describe EmailSettingsValidator dostub(message: "invalid credentials"),)expect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,@@ -199,7 +219,7 @@ RSpec.describe EmailSettingsValidator doit "uses the correct ssl verify params for enable_tls if those settings are enabled" donet_smtp_stub.expects(:enable_tls)expect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: 465,username: username,@@ -215,7 +235,7 @@ RSpec.describe EmailSettingsValidator doit "uses the correct ssl verify params for enable_starttls_auto if those settings are enabled" donet_smtp_stub.expects(:enable_starttls_auto)expect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: 587,username: username,@@ -230,7 +250,7 @@ RSpec.describe EmailSettingsValidator doit "raises an ArgumentError if both enable_tls is true and enable_starttls_auto is true" doexpect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,@@ -244,7 +264,7 @@ RSpec.describe EmailSettingsValidator doit "raises an ArgumentError if a bad authentication method is used" doexpect {- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,@@ -259,7 +279,7 @@ RSpec.describe EmailSettingsValidator dolet(:domain) { nil }it "gets the domain from the host" donet_smtp_stub.expects(:start).with("gmail.com", username, password, :plain)- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,@@ -272,7 +292,7 @@ RSpec.describe EmailSettingsValidator doit "uses localhost when in development mode" doRails.env.stubs(:development?).returns(true)net_smtp_stub.expects(:start).with("localhost", username, password, :plain)- subject.class.validate_smtp(+ described_class.validate_smtp(host: host,port: port,username: username,diff --git a/spec/services/external_upload_manager_spec.rb b/spec/services/external_upload_manager_spec.rbindex 6c4a71a6b91..4ef0304a6f9 100644--- a/spec/services/external_upload_manager_spec.rb+++ b/spec/services/external_upload_manager_spec.rb@@ -1,7 +1,10 @@# frozen_string_literal: trueRSpec.describe ExternalUploadManager do+ subject(:manager) { ExternalUploadManager.new(external_upload_stub) }+fab!(:user) { Fabricate(:user) }+let!(:logo_file) { file_from_fixtures("logo.png") }let!(:pdf_file) { file_from_fixtures("large.pdf", "pdf") }let(:object_size) { 1.megabyte }@@ -13,8 +16,6 @@ RSpec.describe ExternalUploadManager dolet!(:external_upload_stub) { Fabricate(:image_external_upload_stub, created_by: user) }let(:s3_bucket_name) { SiteSetting.s3_upload_bucket }- subject { ExternalUploadManager.new(external_upload_stub) }-before doSiteSetting.authorized_extensions += "|pdf"SiteSetting.max_attachment_size_kb = 210.megabytes / 1000@@ -40,7 +41,7 @@ RSpec.describe ExternalUploadManager dodescribe "#can_promote?" doit "returns false if the external stub status is not created" doexternal_upload_stub.update!(status: ExternalUploadStub.statuses[:uploaded])- expect(subject.can_promote?).to eq(false)+ expect(manager.can_promote?).to eq(false)endend@@ -56,7 +57,7 @@ RSpec.describe ExternalUploadManager dobefore { FileHelper.stubs(:download).returns(nil) }it "raises an error" do- expect { subject.transform! }.to raise_error(ExternalUploadManager::DownloadFailedError)+ expect { manager.transform! }.to raise_error(ExternalUploadManager::DownloadFailedError)endend@@ -64,13 +65,13 @@ RSpec.describe ExternalUploadManager dobefore { external_upload_stub.update!(status: ExternalUploadStub.statuses[:uploaded]) }it "raises an error" do- expect { subject.transform! }.to raise_error(ExternalUploadManager::CannotPromoteError)+ expect { manager.transform! }.to raise_error(ExternalUploadManager::CannotPromoteError)endendcontext "when the upload does not get changed in UploadCreator (resized etc.)" doit "copies the stubbed upload on S3 to its new destination and deletes it" do- upload = subject.transform!+ upload = manager.transform!bucket = @fake_s3.bucket(SiteSetting.s3_upload_bucket)expect(@fake_s3.operation_called?(:copy_object)).to eq(true)@@ -80,7 +81,7 @@ RSpec.describe ExternalUploadManager doit "errors if the image upload is too big" doSiteSetting.max_image_size_kb = 1- upload = subject.transform!+ upload = manager.transform!expect(upload.errors.full_messages).to include("Filesize " +I18n.t(@@ -95,7 +96,7 @@ RSpec.describe ExternalUploadManager doit "errors if the extension is not supported" doSiteSetting.authorized_extensions = ""- upload = subject.transform!+ upload = manager.transform!expect(upload.errors.full_messages).to include("Original filename " + I18n.t("upload.unauthorized", authorized_extensions: ""),)@@ -114,7 +115,7 @@ RSpec.describe ExternalUploadManager doendit "creates a new upload in s3 (not copy) and deletes the original stubbed upload" do- upload = subject.transform!+ upload = manager.transform!bucket = @fake_s3.bucket(SiteSetting.s3_upload_bucket)expect(@fake_s3.operation_called?(:copy_object)).to eq(false)@@ -130,7 +131,7 @@ RSpec.describe ExternalUploadManager dolet(:client_sha1) { "blahblah" }it "raises an error, deletes the stub" do- expect { subject.transform! }.to raise_error(+ expect { manager.transform! }.to raise_error(ExternalUploadManager::ChecksumMismatchError,)expect(ExternalUploadStub.exists?(id: external_upload_stub.id)).to eq(false)@@ -141,7 +142,7 @@ RSpec.describe ExternalUploadManager doit "does not delete the stub if enable_upload_debug_mode" doSiteSetting.enable_upload_debug_mode = true- expect { subject.transform! }.to raise_error(+ expect { manager.transform! }.to raise_error(ExternalUploadManager::ChecksumMismatchError,)external_stub = ExternalUploadStub.find(external_upload_stub.id)@@ -159,7 +160,7 @@ RSpec.describe ExternalUploadManager doafter { Discourse.redis.flushdb }it "raises an error, deletes the file immediately, and prevents the user from uploading external files for a few minutes" do- expect { subject.transform! }.to raise_error(ExternalUploadManager::SizeMismatchError)+ expect { manager.transform! }.to raise_error(ExternalUploadManager::SizeMismatchError)expect(ExternalUploadStub.exists?(id: external_upload_stub.id)).to eq(false)expect(Discourse.redis.get(@@ -173,7 +174,7 @@ RSpec.describe ExternalUploadManager doit "does not delete the stub if enable_upload_debug_mode" doSiteSetting.enable_upload_debug_mode = true- expect { subject.transform! }.to raise_error(ExternalUploadManager::SizeMismatchError)+ expect { manager.transform! }.to raise_error(ExternalUploadManager::SizeMismatchError)external_stub = ExternalUploadStub.find(external_upload_stub.id)expect(external_stub.status).to eq(ExternalUploadStub.statuses[:failed])@@ -199,23 +200,23 @@ RSpec.describe ExternalUploadManager doit "does not try and download the file" doFileHelper.expects(:download).never- subject.transform!+ manager.transform!endit "generates a fake sha for the upload record" do- upload = subject.transform!+ upload = manager.transform!expect(upload.sha1).not_to eq(sha1)expect(upload.original_sha1).to eq(nil)expect(upload.filesize).to eq(object_size)endit "marks the stub as uploaded" do- subject.transform!+ manager.transform!expect(external_upload_stub.reload.status).to eq(ExternalUploadStub.statuses[:uploaded])endit "copies the stubbed upload on S3 to its new destination and deletes it" do- upload = subject.transform!+ upload = manager.transform!bucket = @fake_s3.bucket(SiteSetting.s3_upload_bucket)expect(bucket.find_object(Discourse.store.get_path_for_upload(upload))).to be_present@@ -240,28 +241,28 @@ RSpec.describe ExternalUploadManager doit "does not try and download the file" doFileHelper.expects(:download).never- subject.transform!+ manager.transform!endit "raises an error when backups are disabled" doSiteSetting.enable_backups = false- expect { subject.transform! }.to raise_error(Discourse::InvalidAccess)+ expect { manager.transform! }.to raise_error(Discourse::InvalidAccess)endit "raises an error when backups are local, not s3" doSiteSetting.backup_location = BackupLocationSiteSetting::LOCAL- expect { subject.transform! }.to raise_error(Discourse::InvalidAccess)+ expect { manager.transform! }.to raise_error(Discourse::InvalidAccess)endit "does not create an upload record" do- expect { subject.transform! }.not_to change { Upload.count }+ expect { manager.transform! }.not_to change { Upload.count }endit "copies the stubbed upload on S3 to its new destination and deletes it" dobucket = @fake_s3.bucket(SiteSetting.s3_backup_bucket)expect(bucket.find_object(external_upload_stub.key)).to be_present- subject.transform!+ manager.transform!expect(bucket.find_object(diff --git a/spec/services/flag_sockpuppets_spec.rb b/spec/services/flag_sockpuppets_spec.rbindex 8e921a72b4c..4f77d79b215 100644--- a/spec/services/flag_sockpuppets_spec.rb+++ b/spec/services/flag_sockpuppets_spec.rb@@ -5,9 +5,10 @@ RSpec.describe SpamRule::FlagSockpuppets dofab!(:post1) { Fabricate(:post, user: user1, topic: Fabricate(:topic, user: user1)) }describe "#perform" do- let(:rule) { described_class.new(post1) }subject(:perform) { rule.perform }+ let(:rule) { described_class.new(post1) }+it "does nothing if flag_sockpuppets is disabled" doSiteSetting.flag_sockpuppets = falserule.expects(:reply_is_from_sockpuppet?).neverdiff --git a/spec/services/group_action_logger_spec.rb b/spec/services/group_action_logger_spec.rbindex 28eb7865759..6e7b8c07896 100644--- a/spec/services/group_action_logger_spec.rb+++ b/spec/services/group_action_logger_spec.rb@@ -1,17 +1,17 @@# frozen_string_literal: trueRSpec.describe GroupActionLogger do+ subject(:logger) { described_class.new(group_owner, group) }+fab!(:group_owner) { Fabricate(:user) }fab!(:group) { Fabricate(:group) }fab!(:user) { Fabricate(:user) }- subject { described_class.new(group_owner, group) }-before { group.add_owner(group_owner) }describe "#log_make_user_group_owner" doit "should create the right record" do- subject.log_make_user_group_owner(user)+ logger.log_make_user_group_owner(user)group_history = GroupHistory.last@@ -23,7 +23,7 @@ RSpec.describe GroupActionLogger dodescribe "#log_remove_user_as_group_owner" doit "should create the right record" do- subject.log_remove_user_as_group_owner(user)+ logger.log_remove_user_as_group_owner(user)group_history = GroupHistory.last@@ -36,7 +36,7 @@ RSpec.describe GroupActionLogger dodescribe "#log_add_user_to_group" docontext "as a group owner" doit "should create the right record" do- subject.log_add_user_to_group(user)+ logger.log_add_user_to_group(user)group_history = GroupHistory.last@@ -47,12 +47,12 @@ RSpec.describe GroupActionLogger doendcontext "as a normal user" do- subject { described_class.new(user, group) }+ subject(:logger) { described_class.new(user, group) }before { group.update!(public_admission: true) }it "should create the right record" do- subject.log_add_user_to_group(user)+ logger.log_add_user_to_group(user)group_history = GroupHistory.last@@ -66,7 +66,7 @@ RSpec.describe GroupActionLogger dodescribe "#log_remove_user_from_group" docontext "as group owner" doit "should create the right record" do- subject.log_remove_user_from_group(user)+ logger.log_remove_user_from_group(user)group_history = GroupHistory.last@@ -77,12 +77,12 @@ RSpec.describe GroupActionLogger doendcontext "as a normal user" do- subject { described_class.new(user, group) }+ subject(:logger) { described_class.new(user, group) }before { group.update!(public_exit: true) }it "should create the right record" do- subject.log_remove_user_from_group(user)+ logger.log_remove_user_from_group(user)group_history = GroupHistory.last@@ -97,7 +97,7 @@ RSpec.describe GroupActionLogger doit "should create the right record" dogroup.update!(public_admission: true, created_at: Time.zone.now)- expect { subject.log_change_group_settings }.to change { GroupHistory.count }.by(1)+ expect { logger.log_change_group_settings }.to change { GroupHistory.count }.by(1)group_history = GroupHistory.lastdiff --git a/spec/services/group_message_spec.rb b/spec/services/group_message_spec.rbindex 6ff2e5911d5..4cd007becfc 100644--- a/spec/services/group_message_spec.rb+++ b/spec/services/group_message_spec.rb@@ -1,6 +1,10 @@# frozen_string_literal: trueRSpec.describe GroupMessage do+ subject(:send_group_message) do+ GroupMessage.create(moderators_group, :user_automatically_silenced, user: user)+ end+let(:moderators_group) { Group[:moderators].name }let!(:admin) { Fabricate.build(:admin, id: 999) }@@ -8,10 +12,6 @@ RSpec.describe GroupMessage dobefore { Discourse.stubs(:system_user).returns(admin) }- subject(:send_group_message) do- GroupMessage.create(moderators_group, :user_automatically_silenced, user: user)- end-describe "not sent recently" dobefore { GroupMessage.any_instance.stubs(:sent_recently?).returns(false) }@@ -42,14 +42,17 @@ RSpec.describe GroupMessage doenddescribe "sent recently" do+ subject(:group_message) do+ GroupMessage.create(moderators_group, :user_automatically_silenced, user: user)+ end+before { GroupMessage.any_instance.stubs(:sent_recently?).returns(true) }- subject { GroupMessage.create(moderators_group, :user_automatically_silenced, user: user) }it { is_expected.to eq(false) }it "should not send the same notification again" doPostCreator.expects(:create).never- subject+ group_messageendend@@ -57,29 +60,35 @@ RSpec.describe GroupMessage dolet(:user) { Fabricate.build(:user, id: 123_123) }shared_examples "common message params for group messages" doit "returns the correct params" do- expect(subject[:username]).to eq(user.username)- expect(subject[:user_url]).to be_present+ expect(message_params[:username]).to eq(user.username)+ expect(message_params[:user_url]).to be_presentendendcontext "with user_automatically_silenced" do- subject do+ subject(:message_params) doGroupMessage.new(moderators_group, :user_automatically_silenced, user: user).message_paramsend+include_examples "common message params for group messages"endcontext "with spam_post_blocked" do- subject { GroupMessage.new(moderators_group, :spam_post_blocked, user: user).message_params }+ subject(:message_params) do+ GroupMessage.new(moderators_group, :spam_post_blocked, user: user).message_params+ end+include_examples "common message params for group messages"endenddescribe "methods that use redis" do- let(:user) { Fabricate.build(:user, id: 123_123) }subject(:group_message) doGroupMessage.new(moderators_group, :user_automatically_silenced, user: user)end++ let(:user) { Fabricate.build(:user, id: 123_123) }+before doPostCreator.stubs(:create).returns(stub_everything)group_message.stubs(:sent_recently_key).returns("the_key")diff --git a/spec/services/hashtag_autocomplete_service_spec.rb b/spec/services/hashtag_autocomplete_service_spec.rbindex fce479967df..4b8912a83bc 100644--- a/spec/services/hashtag_autocomplete_service_spec.rb+++ b/spec/services/hashtag_autocomplete_service_spec.rb@@ -1,15 +1,16 @@# frozen_string_literal: trueRSpec.describe HashtagAutocompleteService do+ subject(:service) { described_class.new(guardian) }+fab!(:user) { Fabricate(:user) }fab!(:category1) { Fabricate(:category, name: "The Book Club", slug: "the-book-club") }fab!(:tag1) doFabricate(:tag, name: "great-books", staff_topic_count: 22, public_topic_count: 22)endfab!(:topic1) { Fabricate(:topic) }- let(:guardian) { Guardian.new(user) }- subject { described_class.new(guardian) }+ let(:guardian) { Guardian.new(user) }after { DiscoursePluginRegistry.reset! }@@ -42,24 +43,24 @@ RSpec.describe HashtagAutocompleteService dodescribe "#search" doit "returns search results for tags and categories by default" do- expect(subject.search("book", %w[category tag]).map(&:text)).to eq(+ expect(service.search("book", %w[category tag]).map(&:text)).to eq(["The Book Club", "great-books"],)endit "respects the types_in_priority_order param" do- expect(subject.search("book", %w[tag category]).map(&:text)).to eq(+ expect(service.search("book", %w[tag category]).map(&:text)).to eq(["great-books", "The Book Club"],)endit "respects the limit param" do- expect(subject.search("book", %w[tag category], limit: 1).map(&:text)).to eq(["great-books"])+ expect(service.search("book", %w[tag category], limit: 1).map(&:text)).to eq(["great-books"])endit "does not allow more than SEARCH_MAX_LIMIT results to be specified by the limit param" dostub_const(HashtagAutocompleteService, "SEARCH_MAX_LIMIT", 1) do- expect(subject.search("book", %w[category tag], limit: 1000).map(&:text)).to eq(+ expect(service.search("book", %w[category tag], limit: 1000).map(&:text)).to eq(["The Book Club"],)end@@ -68,35 +69,35 @@ RSpec.describe HashtagAutocompleteService doit "does not search other data sources if the limit is reached by earlier type data sources" do# only expected once to try get the exact matches firstDiscourseTagging.expects(:filter_allowed_tags).never- subject.search("the-book", %w[category tag], limit: 1)+ service.search("the-book", %w[category tag], limit: 1)endit "includes the tag count" dotag1.update!(staff_topic_count: 78, public_topic_count: 78)- expect(subject.search("book", %w[tag category]).map(&:text)).to eq(+ expect(service.search("book", %w[tag category]).map(&:text)).to eq(["great-books", "The Book Club"],)endit "does case-insensitive search" do- expect(subject.search("bOOk", %w[category tag]).map(&:text)).to eq(+ expect(service.search("bOOk", %w[category tag]).map(&:text)).to eq(["The Book Club", "great-books"],)endit "can search categories by name or slug" do- expect(subject.search("the-book-club", %w[category]).map(&:text)).to eq(["The Book Club"])- expect(subject.search("Book C", %w[category]).map(&:text)).to eq(["The Book Club"])+ expect(service.search("the-book-club", %w[category]).map(&:text)).to eq(["The Book Club"])+ expect(service.search("Book C", %w[category]).map(&:text)).to eq(["The Book Club"])endit "does not include categories the user cannot access" docategory1.update!(read_restricted: true)- expect(subject.search("book", %w[tag category]).map(&:text)).to eq(["great-books"])+ expect(service.search("book", %w[tag category]).map(&:text)).to eq(["great-books"])endit "does not include tags the user cannot access" doFabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: ["great-books"])- expect(subject.search("book", %w[tag]).map(&:text)).to be_empty+ expect(service.search("book", %w[tag]).map(&:text)).to be_emptyendit "includes other data sources" do@@ -109,7 +110,7 @@ RSpec.describe HashtagAutocompleteService dostub(enabled?: true),)- expect(subject.search("book", %w[category tag bookmark]).map(&:text)).to eq(+ expect(service.search("book", %w[category tag bookmark]).map(&:text)).to eq(["The Book Club", "great-books", "read review of this fantasy book"],)end@@ -117,7 +118,7 @@ RSpec.describe HashtagAutocompleteService doit "handles refs for categories that have a parent" doparent = Fabricate(:category, name: "Hobbies", slug: "hobbies")category1.update!(parent_category: parent)- expect(subject.search("book", %w[category tag]).map(&:ref)).to eq(+ expect(service.search("book", %w[category tag]).map(&:ref)).to eq(%w[hobbies:the-book-club great-books],)category1.update!(parent_category: nil)@@ -125,7 +126,7 @@ RSpec.describe HashtagAutocompleteService doit "appends type suffixes for the ref on conflicting slugs on items that are not the top priority type" doFabricate(:tag, name: "the-book-club")- expect(subject.search("book", %w[category tag]).map(&:ref)).to eq(+ expect(service.search("book", %w[category tag]).map(&:ref)).to eq(%w[the-book-club great-books the-book-club::tag],)@@ -137,7 +138,7 @@ RSpec.describe HashtagAutocompleteService dostub(enabled?: true),)- expect(subject.search("book", %w[category tag bookmark]).map(&:ref)).to eq(+ expect(service.search("book", %w[category tag bookmark]).map(&:ref)).to eq(%w[book-club the-book-club great-books the-book-club::tag],)end@@ -157,7 +158,7 @@ RSpec.describe HashtagAutocompleteService dostub(enabled?: true),)- expect(subject.search("book", %w[bookmark category tag]).map(&:ref)).to eq(+ expect(service.search("book", %w[bookmark category tag]).map(&:ref)).to eq(%w[book-club hobbies:the-book-club great-books the-book-club::tag],)end@@ -175,7 +176,7 @@ RSpec.describe HashtagAutocompleteService dostub(enabled?: true),)- expect(subject.search("book", %w[bookmark category tag]).map(&:ref)).to eq(+ expect(service.search("book", %w[bookmark category tag]).map(&:ref)).to eq(%w[the-book-club hobbies:the-book-club::category great-books the-book-club::tag],)end@@ -194,7 +195,7 @@ RSpec.describe HashtagAutocompleteService doFabricate(:tag, name: "bookmania", staff_topic_count: 15, public_topic_count: 15)Fabricate(:tag, name: "awful-books", staff_topic_count: 56, public_topic_count: 56)- expect(subject.search("book", %w[category tag]).map(&:ref)).to eq(+ expect(service.search("book", %w[category tag]).map(&:ref)).to eq(["book-reviews:book", # category exact match on slug, name sorted"book-library:book",@@ -208,7 +209,7 @@ RSpec.describe HashtagAutocompleteService do"great-books",],)- expect(subject.search("book", %w[category tag]).map(&:text)).to eq(+ expect(service.search("book", %w[category tag]).map(&:text)).to eq(["Good Books","Horror",@@ -233,13 +234,13 @@ RSpec.describe HashtagAutocompleteService dofab!(:tag4) { Fabricate(:tag, name: "book") }it "orders them by name within their type order" do- expect(subject.search("book", %w[category tag], limit: 10).map(&:ref)).to eq(+ expect(service.search("book", %w[category tag], limit: 10).map(&:ref)).to eq(%w[book book::tag book-dome book-zone the-book-club great-books mid-books terrible-books],)endit "prioritises exact matches to the top of the list" do- expect(subject.search("book", %w[category tag], limit: 10).map(&:ref)).to eq(+ expect(service.search("book", %w[category tag], limit: 10).map(&:ref)).to eq(%w[book book::tag book-dome book-zone the-book-club great-books mid-books terrible-books],)end@@ -249,7 +250,7 @@ RSpec.describe HashtagAutocompleteService dobefore { SiteSetting.tagging_enabled = false }it "does not return any tags" do- expect(subject.search("book", %w[category tag]).map(&:text)).to eq(["The Book Club"])+ expect(service.search("book", %w[category tag]).map(&:text)).to eq(["The Book Club"])endend@@ -274,7 +275,7 @@ RSpec.describe HashtagAutocompleteService docategory1.update!(read_restricted: true)Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: ["terrible-books"])- expect(subject.search(nil, %w[category tag]).map(&:text)).to eq(+ expect(service.search(nil, %w[category tag]).map(&:text)).to eq(["Book Dome","Book Zone",@@ -294,7 +295,7 @@ RSpec.describe HashtagAutocompleteService dofab!(:tag2) { Fabricate(:tag, name: "fiction-books") }it "returns categories and tags in a hash format with the slug and url" do- result = subject.lookup_old(%w[the-book-club great-books fiction-books])+ result = service.lookup_old(%w[the-book-club great-books fiction-books])expect(result[:categories]).to eq({ "the-book-club" => "/c/the-book-club/#{category1.id}" })expect(result[:tags]).to eq({@@ -306,18 +307,18 @@ RSpec.describe HashtagAutocompleteService doit "does not include categories the user cannot access" docategory1.update!(read_restricted: true)- result = subject.lookup_old(%w[the-book-club great-books fiction-books])+ result = service.lookup_old(%w[the-book-club great-books fiction-books])expect(result[:categories]).to eq({})endit "does not include tags the user cannot access" doFabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: ["great-books"])- result = subject.lookup_old(%w[the-book-club great-books fiction-books])+ result = service.lookup_old(%w[the-book-club great-books fiction-books])expect(result[:tags]).to eq({ "fiction-books" => "http://test.localhost/tag/fiction-books" })endit "handles tags which have the ::tag suffix" do- result = subject.lookup_old(%w[the-book-club great-books::tag fiction-books])+ result = service.lookup_old(%w[the-book-club great-books::tag fiction-books])expect(result[:tags]).to eq({"fiction-books" => "http://test.localhost/tag/fiction-books",@@ -330,7 +331,7 @@ RSpec.describe HashtagAutocompleteService dobefore { SiteSetting.tagging_enabled = false }it "does not return tags" do- result = subject.lookup_old(%w[the-book-club great-books fiction-books])+ result = service.lookup_old(%w[the-book-club great-books fiction-books])expect(result[:categories]).to eq({ "the-book-club" => "/c/the-book-club/#{category1.id}" })expect(result[:tags]).to eq({})end@@ -341,7 +342,7 @@ RSpec.describe HashtagAutocompleteService dofab!(:tag2) { Fabricate(:tag, name: "fiction-books") }it "returns category and tag in a hash format with the slug and url" do- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:category].map(&:slug)).to eq(["the-book-club"])expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books])@@ -350,20 +351,20 @@ RSpec.describe HashtagAutocompleteService doit "does not include category the user cannot access" docategory1.update!(read_restricted: true)- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:category]).to eq([])endit "does not include tag the user cannot access" doFabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: ["great-books"])- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:tag].map(&:slug)).to eq(%w[fiction-books])expect(result[:tag].map(&:relative_url)).to eq(["/tag/fiction-books"])endit "handles type suffixes for slugs" doresult =- subject.lookup(%w[the-book-club::category great-books::tag fiction-books], %w[category tag])+ service.lookup(%w[the-book-club::category great-books::tag fiction-books], %w[category tag])expect(result[:category].map(&:slug)).to eq(["the-book-club"])expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books])@@ -373,7 +374,7 @@ RSpec.describe HashtagAutocompleteService doit "handles parent:child category lookups" doparent_category = Fabricate(:category, name: "Media", slug: "media")category1.update!(parent_category: parent_category)- result = subject.lookup(%w[media:the-book-club], %w[category tag])+ result = service.lookup(%w[media:the-book-club], %w[category tag])expect(result[:category].map(&:slug)).to eq(["the-book-club"])expect(result[:category].map(&:ref)).to eq(["media:the-book-club"])expect(result[:category].map(&:relative_url)).to eq(@@ -385,7 +386,7 @@ RSpec.describe HashtagAutocompleteService doit "handles parent:child category lookups with type suffix" doparent_category = Fabricate(:category, name: "Media", slug: "media")category1.update!(parent_category: parent_category)- result = subject.lookup(%w[media:the-book-club::category], %w[category tag])+ result = service.lookup(%w[media:the-book-club::category], %w[category tag])expect(result[:category].map(&:slug)).to eq(["the-book-club"])expect(result[:category].map(&:ref)).to eq(["media:the-book-club::category"])expect(result[:category].map(&:relative_url)).to eq(@@ -397,19 +398,19 @@ RSpec.describe HashtagAutocompleteService doit "does not return the category if the parent does not match the child" doparent_category = Fabricate(:category, name: "Media", slug: "media")category1.update!(parent_category: parent_category)- result = subject.lookup(%w[bad-parent:the-book-club], %w[category tag])+ result = service.lookup(%w[bad-parent:the-book-club], %w[category tag])expect(result[:category]).to be_emptyendit "for slugs without a type suffix it falls back in type order until a result is found or types are exhausted" do- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:category].map(&:slug)).to eq(["the-book-club"])expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books])expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books /tag/great-books])category2 = Fabricate(:category, name: "Great Books", slug: "great-books")- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:category].map(&:slug)).to eq(%w[great-books the-book-club])expect(result[:category].map(&:relative_url)).to eq(["/c/great-books/#{category2.id}", "/c/the-book-club/#{category1.id}"],@@ -419,13 +420,13 @@ RSpec.describe HashtagAutocompleteService docategory1.destroy!Fabricate(:tag, name: "the-book-club")- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:category].map(&:slug)).to eq(["great-books"])expect(result[:category].map(&:relative_url)).to eq(["/c/great-books/#{category2.id}"])expect(result[:tag].map(&:slug)).to eq(%w[fiction-books the-book-club])expect(result[:tag].map(&:relative_url)).to eq(%w[/tag/fiction-books /tag/the-book-club])- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[tag category])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[tag category])expect(result[:category]).to eq([])expect(result[:tag].map(&:slug)).to eq(%w[fiction-books great-books the-book-club])expect(result[:tag].map(&:relative_url)).to eq(@@ -443,14 +444,14 @@ RSpec.describe HashtagAutocompleteService dostub(enabled?: true),)- result = subject.lookup(["coolrock"], %w[category tag bookmark])+ result = service.lookup(["coolrock"], %w[category tag bookmark])expect(result[:bookmark].map(&:slug)).to eq(["coolrock"])endit "handles type suffix lookups where there is another type with a conflicting slug that the user cannot access" docategory1.update!(read_restricted: true)Fabricate(:tag, name: "the-book-club")- result = subject.lookup(%w[the-book-club::tag the-book-club], %w[category tag])+ result = service.lookup(%w[the-book-club::tag the-book-club], %w[category tag])expect(result[:category].map(&:ref)).to eq([])expect(result[:tag].map(&:ref)).to eq(["the-book-club::tag"])end@@ -459,7 +460,7 @@ RSpec.describe HashtagAutocompleteService dobefore { SiteSetting.tagging_enabled = false }it "does not return tag" do- result = subject.lookup(%w[the-book-club great-books fiction-books], %w[category tag])+ result = service.lookup(%w[the-book-club great-books fiction-books], %w[category tag])expect(result[:category].map(&:slug)).to eq(["the-book-club"])expect(result[:category].map(&:relative_url)).to eq(["/c/the-book-club/#{category1.id}"])expect(result[:tag]).to eq([])diff --git a/spec/services/notifications/consolidation_planner_spec.rb b/spec/services/notifications/consolidation_planner_spec.rbindex 707d719e4a0..5e9526b4472 100644--- a/spec/services/notifications/consolidation_planner_spec.rb+++ b/spec/services/notifications/consolidation_planner_spec.rb@@ -1,6 +1,8 @@# frozen_string_literal: trueRSpec.describe Notifications::ConsolidationPlanner do+ subject(:planner) { described_class.new }+describe "#consolidate_or_save!" dolet(:threshold) { 1 }fab!(:user) { Fabricate(:user) }@@ -11,7 +13,7 @@ RSpec.describe Notifications::ConsolidationPlanner doit "does nothing it haven't passed the consolidation threshold yet" donotification = build_notification(:liked, { display_username: like_user })- saved_like = subject.consolidate_or_save!(notification)+ saved_like = planner.consolidate_or_save!(notification)expect(saved_like.id).to be_presentexpect(saved_like.notification_type).to eq(Notification.types[:liked])@@ -27,7 +29,7 @@ RSpec.describe Notifications::ConsolidationPlanner do)notification = build_notification(:liked, { display_username: like_user })- consolidated_like = subject.consolidate_or_save!(notification)+ consolidated_like = planner.consolidate_or_save!(notification)expect(consolidated_like.id).not_to eq(first_notification.id)expect(consolidated_like.notification_type).to eq(Notification.types[:liked_consolidated])@@ -45,7 +47,7 @@ RSpec.describe Notifications::ConsolidationPlanner do)notification = build_notification(:liked, { display_username: like_user })- updated = subject.consolidate_or_save!(notification)+ updated = planner.consolidate_or_save!(notification)expect { notification.reload }.to raise_error(ActiveRecord::RecordNotFound)data = JSON.parse(updated.data)@@ -63,6 +65,6 @@ RSpec.describe Notifications::ConsolidationPlanner doenddef plan_for(notification)- subject.plan_for(notification)+ planner.plan_for(notification)endenddiff --git a/spec/services/post_bookmarkable_spec.rb b/spec/services/post_bookmarkable_spec.rbindex 94fed97f9af..dbd1d8855ca 100644--- a/spec/services/post_bookmarkable_spec.rb+++ b/spec/services/post_bookmarkable_spec.rb@@ -3,10 +3,13 @@require "rails_helper"RSpec.describe PostBookmarkable do+ subject(:registered_bookmarkable) { RegisteredBookmarkable.new(PostBookmarkable) }+fab!(:user) { Fabricate(:user) }- let(:guardian) { Guardian.new(user) }fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }+ let(:guardian) { Guardian.new(user) }+let!(:post1) { Fabricate(:post) }let!(:post2) { Fabricate(:post) }let!(:bookmark1) do@@ -17,23 +20,25 @@ RSpec.describe PostBookmarkable dolet!(:topic_user1) { Fabricate(:topic_user, user: user, topic: post1.topic) }let!(:topic_user2) { Fabricate(:topic_user, user: user, topic: post2.topic) }- subject { RegisteredBookmarkable.new(PostBookmarkable) }-describe "#perform_list_query" doit "returns all the user's bookmarks" do- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array(+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark1.id, bookmark2.id],)endit "does not return bookmarks for posts where the user does not have access to the topic category" dobookmark1.bookmarkable.topic.update(category: private_category)- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark2.id])+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array(+ [bookmark2.id],+ )endit "does not return bookmarks for posts where the user does not have access to the private message" dobookmark1.bookmarkable.update(topic: Fabricate(:private_message_topic))- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark2.id])+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array(+ [bookmark2.id],+ )endend@@ -43,8 +48,8 @@ RSpec.describe PostBookmarkable doit "returns bookmarks that match by name" dots_query = Search.ts_query(term: "gotta", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%gotta%",ts_query,).map(&:id),@@ -57,8 +62,8 @@ RSpec.describe PostBookmarkable dots_query = Search.ts_query(term: "post content", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%post content%",ts_query,).map(&:id),@@ -66,8 +71,8 @@ RSpec.describe PostBookmarkable dots_query = Search.ts_query(term: "great topic", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%great topic%",ts_query,).map(&:id),@@ -75,8 +80,8 @@ RSpec.describe PostBookmarkable dots_query = Search.ts_query(term: "blah", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%blah%",ts_query,).map(&:id),@@ -86,23 +91,23 @@ RSpec.describe PostBookmarkable dodescribe "#can_send_reminder?" doit "cannot send reminder if the post or topic is deleted" do- expect(subject.can_send_reminder?(bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(true)bookmark1.bookmarkable.trash!bookmark1.reload- expect(subject.can_send_reminder?(bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)Post.with_deleted.find_by(id: bookmark1.bookmarkable_id).recover!bookmark1.reloadbookmark1.bookmarkable.topic.trash!bookmark1.reload- expect(subject.can_send_reminder?(bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)endenddescribe "#reminder_handler" doit "creates a notification for the user with the correct details" do- expect { subject.send_reminder_notification(bookmark1) }.to change { Notification.count }.by(- 1,- )+ expect { registered_bookmarkable.send_reminder_notification(bookmark1) }.to change {+ Notification.count+ }.by(1)notif = user.notifications.lastexpect(notif.notification_type).to eq(Notification.types[:bookmark_reminder])expect(notif.topic_id).to eq(bookmark1.bookmarkable.topic_id)@@ -121,11 +126,11 @@ RSpec.describe PostBookmarkable dodescribe "#can_see?" doit "returns false if the post is in a private category or private message the user cannot see" do- expect(subject.can_see?(guardian, bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(true)bookmark1.bookmarkable.topic.update(category: private_category)- expect(subject.can_see?(guardian, bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(false)bookmark1.bookmarkable.update(topic: Fabricate(:private_message_topic))- expect(subject.can_see?(guardian, bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(false)endendenddiff --git a/spec/services/post_owner_changer_spec.rb b/spec/services/post_owner_changer_spec.rbindex 70eb1bb3808..ecf44e8c41e 100644--- a/spec/services/post_owner_changer_spec.rb+++ b/spec/services/post_owner_changer_spec.rb@@ -171,6 +171,15 @@ RSpec.describe PostOwnerChanger doendcontext "with integration tests" do+ subject(:change_owners) do+ PostOwnerChanger.new(+ post_ids: [p1.id, p2.id],+ topic_id: topic.id,+ new_owner: user_a,+ acting_user: editor,+ ).change_owner!+ end+let(:p1user) { p1.user }let(:p2user) { p2.user }@@ -209,15 +218,6 @@ RSpec.describe PostOwnerChanger doUserActionManager.enableend- subject(:change_owners) do- PostOwnerChanger.new(- post_ids: [p1.id, p2.id],- topic_id: topic.id,- new_owner: user_a,- acting_user: editor,- ).change_owner!- end-it "updates users' topic and post counts" doPostActionCreator.like(p2user, p1)expect(p1user.user_stat.reload.likes_received).to eq(1)diff --git a/spec/services/staff_action_logger_spec.rb b/spec/services/staff_action_logger_spec.rbindex 4241857bf64..b1a9cfa660e 100644--- a/spec/services/staff_action_logger_spec.rb+++ b/spec/services/staff_action_logger_spec.rb@@ -15,10 +15,10 @@ RSpec.describe StaffActionLogger doenddescribe "log_user_deletion" do- fab!(:deleted_user) { Fabricate(:user) }-subject(:log_user_deletion) { described_class.new(admin).log_user_deletion(deleted_user) }+ fab!(:deleted_user) { Fabricate(:user) }+it "raises an error when user is nil" doexpect { logger.log_user_deletion(nil) }.to raise_error(Discourse::InvalidParameters)end@@ -47,10 +47,10 @@ RSpec.describe StaffActionLogger doenddescribe "log_post_deletion" do- fab!(:deleted_post) { Fabricate(:post) }-subject(:log_post_deletion) { described_class.new(admin).log_post_deletion(deleted_post) }+ fab!(:deleted_post) { Fabricate(:post) }+it "raises an error when post is nil" doexpect { logger.log_post_deletion(nil) }.to raise_error(Discourse::InvalidParameters)end@@ -116,14 +116,15 @@ RSpec.describe StaffActionLogger doenddescribe "log_trust_level_change" do- fab!(:user) { Fabricate(:user) }- let(:old_trust_level) { TrustLevel[0] }- let(:new_trust_level) { TrustLevel[1] }-subject(:log_trust_level_change) dodescribed_class.new(admin).log_trust_level_change(user, old_trust_level, new_trust_level)end+ fab!(:user) { Fabricate(:user) }++ let(:old_trust_level) { TrustLevel[0] }+ let(:new_trust_level) { TrustLevel[1] }+it "raises an error when user or trust level is nil" doexpect {logger.log_trust_level_change(nil, old_trust_level, new_trust_level)@@ -371,11 +372,11 @@ RSpec.describe StaffActionLogger doenddescribe "log_roll_up" do+ subject(:log_roll_up) { described_class.new(admin).log_roll_up(subnet, ips) }+let(:subnet) { "1.2.3.0/24" }let(:ips) { %w[1.2.3.4 1.2.3.100] }- subject(:log_roll_up) { described_class.new(admin).log_roll_up(subnet, ips) }-it "creates a new UserHistory record" dolog_record = logger.log_roll_up(subnet, ips)expect(log_record).to be_valid@@ -584,12 +585,12 @@ RSpec.describe StaffActionLogger doenddescribe "log_check_personal_message" do- fab!(:personal_message) { Fabricate(:private_message_topic) }-subject(:log_check_personal_message) dodescribed_class.new(admin).log_check_personal_message(personal_message)end+ fab!(:personal_message) { Fabricate(:private_message_topic) }+it "raises an error when topic is nil" doexpect { logger.log_check_personal_message(nil) }.to raise_error(Discourse::InvalidParameters)end@@ -604,10 +605,10 @@ RSpec.describe StaffActionLogger doenddescribe "log_post_approved" do- fab!(:approved_post) { Fabricate(:post) }-subject(:log_post_approved) { described_class.new(admin).log_post_approved(approved_post) }+ fab!(:approved_post) { Fabricate(:post) }+it "raises an error when post is nil" doexpect { logger.log_post_approved(nil) }.to raise_error(Discourse::InvalidParameters)end@@ -622,12 +623,12 @@ RSpec.describe StaffActionLogger doenddescribe "log_post_rejected" do- fab!(:reviewable) { Fabricate(:reviewable_queued_post) }-subject(:log_post_rejected) dodescribed_class.new(admin).log_post_rejected(reviewable, DateTime.now)end+ fab!(:reviewable) { Fabricate(:reviewable_queued_post) }+it "raises an error when reviewable not supplied" doexpect { logger.log_post_rejected(nil, DateTime.now) }.to raise_error(Discourse::InvalidParameters,diff --git a/spec/services/topic_bookmarkable_spec.rb b/spec/services/topic_bookmarkable_spec.rbindex ac2ad2454b4..b5aa7685974 100644--- a/spec/services/topic_bookmarkable_spec.rb+++ b/spec/services/topic_bookmarkable_spec.rb@@ -3,10 +3,13 @@require "rails_helper"RSpec.describe TopicBookmarkable do+ subject(:registered_bookmarkable) { RegisteredBookmarkable.new(TopicBookmarkable) }+fab!(:user) { Fabricate(:user) }- let(:guardian) { Guardian.new(user) }fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }+ let(:guardian) { Guardian.new(user) }+let!(:topic1) { Fabricate(:topic) }let!(:topic2) { Fabricate(:topic) }let!(:post) { Fabricate(:post, topic: topic1) }@@ -18,23 +21,25 @@ RSpec.describe TopicBookmarkable dolet!(:topic_user1) { Fabricate(:topic_user, user: user, topic: topic1) }let!(:topic_user2) { Fabricate(:topic_user, user: user, topic: topic2) }- subject { RegisteredBookmarkable.new(TopicBookmarkable) }-describe "#perform_list_query" doit "returns all the user's bookmarks" do- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array(+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark1.id, bookmark2.id],)endit "does not return bookmarks for posts where the user does not have access to the topic category" dobookmark1.bookmarkable.update!(category: private_category)- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark2.id])+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array(+ [bookmark2.id],+ )endit "does not return bookmarks for posts where the user does not have access to the private message" dobookmark1.update!(bookmarkable: Fabricate(:private_message_topic))- expect(subject.perform_list_query(user, guardian).map(&:id)).to match_array([bookmark2.id])+ expect(registered_bookmarkable.perform_list_query(user, guardian).map(&:id)).to match_array(+ [bookmark2.id],+ )endend@@ -44,8 +49,8 @@ RSpec.describe TopicBookmarkable doit "returns bookmarks that match by name" dots_query = Search.ts_query(term: "gotta", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%gotta%",ts_query,).map(&:id),@@ -58,8 +63,8 @@ RSpec.describe TopicBookmarkable dots_query = Search.ts_query(term: "post content", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%post content%",ts_query,).map(&:id),@@ -67,8 +72,8 @@ RSpec.describe TopicBookmarkable dots_query = Search.ts_query(term: "great topic", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%great topic%",ts_query,).map(&:id),@@ -76,8 +81,8 @@ RSpec.describe TopicBookmarkable dots_query = Search.ts_query(term: "blah", ts_config: "simple")expect(- subject.perform_search_query(- subject.perform_list_query(user, guardian),+ registered_bookmarkable.perform_search_query(+ registered_bookmarkable.perform_list_query(user, guardian),"%blah%",ts_query,).map(&:id),@@ -87,18 +92,18 @@ RSpec.describe TopicBookmarkable dodescribe "#can_send_reminder?" doit "cannot send reminder if the topic is deleted" do- expect(subject.can_send_reminder?(bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(true)bookmark1.bookmarkable.trash!bookmark1.reload- expect(subject.can_send_reminder?(bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)endenddescribe "#reminder_handler" doit "creates a notification for the user with the correct details" do- expect { subject.send_reminder_notification(bookmark1) }.to change { Notification.count }.by(- 1,- )+ expect { registered_bookmarkable.send_reminder_notification(bookmark1) }.to change {+ Notification.count+ }.by(1)notif = user.notifications.lastexpect(notif.notification_type).to eq(Notification.types[:bookmark_reminder])expect(notif.topic_id).to eq(bookmark1.bookmarkable_id)@@ -117,11 +122,11 @@ RSpec.describe TopicBookmarkable dodescribe "#can_see?" doit "returns false if the post is in a private category or private message the user cannot see" do- expect(subject.can_see?(guardian, bookmark1)).to eq(true)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(true)bookmark1.bookmarkable.update!(category: private_category)- expect(subject.can_see?(guardian, bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(false)bookmark1.update!(bookmarkable: Fabricate(:private_message_topic))- expect(subject.can_see?(guardian, bookmark1)).to eq(false)+ expect(registered_bookmarkable.can_see?(guardian, bookmark1)).to eq(false)endendenddiff --git a/spec/services/user_anonymizer_spec.rb b/spec/services/user_anonymizer_spec.rbindex e79845ee628..d82e2e2c77e 100644--- a/spec/services/user_anonymizer_spec.rb+++ b/spec/services/user_anonymizer_spec.rb@@ -4,11 +4,12 @@ RSpec.describe UserAnonymizer dolet(:admin) { Fabricate(:admin) }describe "event" do- let(:user) { Fabricate(:user, username: "edward") }subject(:make_anonymous) dodescribed_class.make_anonymous(user, admin, anonymize_ip: "2.2.2.2")end+ let(:user) { Fabricate(:user, username: "edward") }+it "triggers the event" doevents = DiscourseEvent.track_events { make_anonymous }@@ -22,10 +23,11 @@ RSpec.describe UserAnonymizer doenddescribe ".make_anonymous" do+ subject(:make_anonymous) { described_class.make_anonymous(user, admin) }+let(:original_email) { "[email protected]" }let(:user) { Fabricate(:user, username: "edward", email: original_email) }fab!(:another_user) { Fabricate(:evil_trout) }- subject(:make_anonymous) { described_class.make_anonymous(user, admin) }it "changes username" domake_anonymousdiff --git a/spec/services/user_destroyer_spec.rb b/spec/services/user_destroyer_spec.rbindex 48210ff932b..46df20a9a75 100644--- a/spec/services/user_destroyer_spec.rb+++ b/spec/services/user_destroyer_spec.rb@@ -75,9 +75,10 @@ RSpec.describe UserDestroyer doendcontext "when user deletes self" do- let(:destroy_opts) { { delete_posts: true, context: "/u/username/preferences/account" } }subject(:destroy) { UserDestroyer.new(user).destroy(user, destroy_opts) }+ let(:destroy_opts) { { delete_posts: true, context: "/u/username/preferences/account" } }+include_examples "successfully destroy a user"it "should log proper context" do@@ -147,6 +148,7 @@ RSpec.describe UserDestroyer docontext "when delete_posts is false" dosubject(:destroy) { UserDestroyer.new(admin).destroy(user) }+before douser.stubs(:post_count).returns(1)user.stubs(:first_post_created_at).returns(Time.zone.now)@@ -253,18 +255,21 @@ RSpec.describe UserDestroyer doendcontext "when user has no posts, but user_stats table has post_count > 0" do+ subject(:destroy) { UserDestroyer.new(user).destroy(user, delete_posts: false) }++ let(:destroy_opts) { {} }+before do# out of sync user_stat data shouldn't break UserDestroyeruser.user_stat.update_attribute(:post_count, 1)end- let(:destroy_opts) { {} }- subject(:destroy) { UserDestroyer.new(user).destroy(user, delete_posts: false) }include_examples "successfully destroy a user"endcontext "when user has deleted posts" dolet!(:deleted_post) { Fabricate(:post, user: user, deleted_at: 1.hour.ago) }+it "should mark the user's deleted posts as belonging to a nuked user" doexpect { UserDestroyer.new(admin).destroy(user) }.to change { User.count }.by(-1)expect(deleted_post.reload.user_id).to eq(nil)@@ -273,9 +278,10 @@ RSpec.describe UserDestroyer docontext "when user has no posts" docontext "when destroy succeeds" do- let(:destroy_opts) { {} }subject(:destroy) { UserDestroyer.new(admin).destroy(user) }+ let(:destroy_opts) { {} }+include_examples "successfully destroy a user"include_examples "email block list"enddiff --git a/spec/services/user_silencer_spec.rb b/spec/services/user_silencer_spec.rbindex b637fc6e9db..4a0b548d38e 100644--- a/spec/services/user_silencer_spec.rb+++ b/spec/services/user_silencer_spec.rb@@ -6,9 +6,10 @@ RSpec.describe UserSilencer dofab!(:admin) { Fabricate(:admin) }describe "silence" do- let(:silencer) { UserSilencer.new(user) }subject(:silence_user) { silencer.silence }+ let(:silencer) { UserSilencer.new(user) }+it "silences the user correctly" doexpect { UserSilencer.silence(user, admin) }.to change { user.reload.silenced? }