DEV: Update the rubocop-discourse gem

This enables cops related to RSpec `subject`.

See https://github.com/discourse/rubocop-discourse/pull/32
This commit is contained in:
Loïc Guitaut
2023-06-21 16:00:19 +02:00
committed by Loïc Guitaut
parent 8e1d049e6b
commit 0f4beab0fb
129 changed files with 1697 additions and 1506 deletions

View File

@@ -9,12 +9,13 @@ RSpec.describe SpamRule::AutoSilence do
end
describe "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.perform
expect(post.user.reload).not_to be_silenced
end
@@ -23,81 +24,84 @@ RSpec.describe SpamRule::AutoSilence do
SiteSetting.silence_new_user_sensitivity = Reviewable.sensitivities[:low]
SiteSetting.num_users_to_silence_new_user = 1
PostActionCreator.spam(Discourse.system_user, post)
subject.perform
autosilence.perform
expect(post.user.reload).to be_silenced
end
end
describe "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)
end
it "returns 0 when there is one flag that has a reason other than spam" do
PostActionCreator.off_topic(flagger, post)
expect(subject).to eq(0)
expect(score).to eq(0)
end
it "returns the score when there are two flags with spam as the reason" do
PostActionCreator.spam(Fabricate(:user), post)
PostActionCreator.spam(Fabricate(:user), post)
expect(subject).to eq(4.0)
expect(score).to eq(4.0)
end
it "returns the score when there are two spam flags, each on a different post" do
PostActionCreator.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)
end
end
describe "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)
end
it "returns 0 when there is one flag that has a reason other than spam" do
Fabricate(:flag, post: post, post_action_type_id: PostActionType.types[:off_topic])
expect(subject).to eq(0)
expect(count).to eq(0)
end
it "returns 1 when there is one spam flag" do
PostActionCreator.spam(Fabricate(:user), post)
expect(subject).to eq(1)
expect(count).to eq(1)
end
it "returns 2 when there are two spam flags from 2 users" do
PostActionCreator.spam(Fabricate(:user), post)
PostActionCreator.spam(Fabricate(:user), post)
expect(subject).to eq(2)
expect(count).to eq(2)
end
it "returns 1 when there are two spam flags on two different posts from 1 user" do
flagger = Fabricate(:user)
PostActionCreator.spam(flagger, post)
PostActionCreator.spam(flagger, Fabricate(:post, user: post.user))
expect(subject).to eq(1)
expect(count).to eq(1)
end
end
describe "#silence_user" do
subject(:autosilence) { described_class.new(user) }
let!(:admin) { Fabricate(:admin) } # needed for SystemMessage
let(:user) { Fabricate(:user) }
let!(:post) { Fabricate(:post, user: user) }
subject { described_class.new(user) }
context "when user is not silenced" do
it "prevents the user from making new posts" do
subject.silence_user
autosilence.silence_user
expect(user).to be_silenced
expect(Guardian.new(user).can_create_post?(nil)).to be_falsey
end
@@ -107,14 +111,14 @@ RSpec.describe SpamRule::AutoSilence do
it "sends private message to moderators" do
SiteSetting.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_present
end
it "doesn't send a pm to moderators if notify_mods_when_user_silenced is false" do
SiteSetting.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_blank
end
end
end
@@ -123,8 +127,8 @@ RSpec.describe SpamRule::AutoSilence do
before { 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_blank
end
end
end
@@ -167,20 +171,21 @@ RSpec.describe SpamRule::AutoSilence do
end
context "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" do
expect(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)
end
it "returns false if there are not received enough flags" do
PostActionCreator.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)
end
it "returns false if there have not been enough users" do
@@ -188,21 +193,21 @@ RSpec.describe SpamRule::AutoSilence do
PostActionCreator.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)
end
it "returns false if silence_new_user_sensitivity is disabled" do
SiteSetting.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)
end
it "returns false if num_users_to_silence_new_user is 0" do
SiteSetting.num_users_to_silence_new_user = 0
PostActionCreator.spam(flagger, post)
PostActionCreator.spam(flagger2, post)
expect(subject.should_autosilence?).to eq(false)
expect(autosilence.should_autosilence?).to eq(false)
end
it "returns true when there are enough flags from enough users" do
@@ -210,16 +215,17 @@ RSpec.describe SpamRule::AutoSilence do
PostActionCreator.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)
end
end
context "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)
end
end
end

View File

@@ -4,21 +4,21 @@ RSpec.describe EmailSettingsExceptionHandler do
describe "#friendly_exception_message" do
it "formats a Net::POPAuthenticationError" do
exception = 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"),
)
end
it "formats a Net::IMAP::NoResponseError for invalid credentials" do
exception = 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"),
)
end
it "formats a general Net::IMAP::NoResponseError" do
exception = 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 do
Net::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"),
)
end
it "formats a Net::SMTPAuthenticationError" do
exception = 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 do
it "formats a Net::SMTPAuthenticationError with application-specific password Gmail error" do
exception =
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"),
)
end
it "formats a Net::SMTPServerBusy" do
exception = 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"),
)
end
it "formats a Net::SMTPSyntaxError, Net::SMTPFatalError, and Net::SMTPUnknownError" do
exception = 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),
)
end
it "formats a SocketError and Errno::ECONNREFUSED" do
exception = 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"),
)
end
it "formats a Net::OpenTimeout and Net::ReadTimeout error" do
exception = 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"),
)
end
it "formats unhandled errors" do
exception = 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),
)
end

View File

@@ -20,7 +20,12 @@ RSpec.describe EmailSettingsValidator do
net_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_error
end
@@ -30,7 +35,7 @@ RSpec.describe EmailSettingsValidator do
stub(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_once
expect {
subject.class.validate_imap(
described_class.validate_imap(
host: host,
port: port,
username: username,
@@ -77,14 +82,19 @@ RSpec.describe EmailSettingsValidator do
it "is valid if no error is raised" do
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_error
end
it "is invalid if an error is raised" do
net_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_once
net_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 do
SiteSetting.pop3_polling_openssl_verify = true
net_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_error
end
@@ -126,7 +141,12 @@ RSpec.describe EmailSettingsValidator do
SiteSetting.pop3_polling_openssl_verify = false
net_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_error
end
end
@@ -151,7 +171,7 @@ RSpec.describe EmailSettingsValidator do
it "is valid if no error is raised" do
expect {
subject.class.validate_smtp(
described_class.validate_smtp(
host: host,
port: port,
username: username,
@@ -164,7 +184,7 @@ RSpec.describe EmailSettingsValidator do
it "is invalid if an error is raised" do
net_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 do
stub(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 do
it "uses the correct ssl verify params for enable_tls if those settings are enabled" do
net_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 do
it "uses the correct ssl verify params for enable_starttls_auto if those settings are enabled" do
net_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 do
it "raises an ArgumentError if both enable_tls is true and enable_starttls_auto is true" do
expect {
subject.class.validate_smtp(
described_class.validate_smtp(
host: host,
port: port,
username: username,
@@ -244,7 +264,7 @@ RSpec.describe EmailSettingsValidator do
it "raises an ArgumentError if a bad authentication method is used" do
expect {
subject.class.validate_smtp(
described_class.validate_smtp(
host: host,
port: port,
username: username,
@@ -259,7 +279,7 @@ RSpec.describe EmailSettingsValidator do
let(:domain) { nil }
it "gets the domain from the host" do
net_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 do
it "uses localhost when in development mode" do
Rails.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,

View File

@@ -1,7 +1,10 @@
# frozen_string_literal: true
RSpec.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 do
let!(: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 do
SiteSetting.authorized_extensions += "|pdf"
SiteSetting.max_attachment_size_kb = 210.megabytes / 1000
@@ -40,7 +41,7 @@ RSpec.describe ExternalUploadManager do
describe "#can_promote?" do
it "returns false if the external stub status is not created" do
external_upload_stub.update!(status: ExternalUploadStub.statuses[:uploaded])
expect(subject.can_promote?).to eq(false)
expect(manager.can_promote?).to eq(false)
end
end
@@ -56,7 +57,7 @@ RSpec.describe ExternalUploadManager do
before { 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)
end
end
@@ -64,13 +65,13 @@ RSpec.describe ExternalUploadManager do
before { 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)
end
end
context "when the upload does not get changed in UploadCreator (resized etc.)" do
it "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 do
it "errors if the image upload is too big" do
SiteSetting.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 do
it "errors if the extension is not supported" do
SiteSetting.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 do
end
it "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 do
let(: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 do
it "does not delete the stub if enable_upload_debug_mode" do
SiteSetting.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 do
after { 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 do
it "does not delete the stub if enable_upload_debug_mode" do
SiteSetting.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 do
it "does not try and download the file" do
FileHelper.expects(:download).never
subject.transform!
manager.transform!
end
it "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)
end
it "marks the stub as uploaded" do
subject.transform!
manager.transform!
expect(external_upload_stub.reload.status).to eq(ExternalUploadStub.statuses[:uploaded])
end
it "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 do
it "does not try and download the file" do
FileHelper.expects(:download).never
subject.transform!
manager.transform!
end
it "raises an error when backups are disabled" do
SiteSetting.enable_backups = false
expect { subject.transform! }.to raise_error(Discourse::InvalidAccess)
expect { manager.transform! }.to raise_error(Discourse::InvalidAccess)
end
it "raises an error when backups are local, not s3" do
SiteSetting.backup_location = BackupLocationSiteSetting::LOCAL
expect { subject.transform! }.to raise_error(Discourse::InvalidAccess)
expect { manager.transform! }.to raise_error(Discourse::InvalidAccess)
end
it "does not create an upload record" do
expect { subject.transform! }.not_to change { Upload.count }
expect { manager.transform! }.not_to change { Upload.count }
end
it "copies the stubbed upload on S3 to its new destination and deletes it" do
bucket = @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(

View File

@@ -5,9 +5,10 @@ RSpec.describe SpamRule::FlagSockpuppets do
fab!(: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" do
SiteSetting.flag_sockpuppets = false
rule.expects(:reply_is_from_sockpuppet?).never

View File

@@ -1,17 +1,17 @@
# frozen_string_literal: true
RSpec.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" do
it "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 do
describe "#log_remove_user_as_group_owner" do
it "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 do
describe "#log_add_user_to_group" do
context "as a group owner" do
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
@@ -47,12 +47,12 @@ RSpec.describe GroupActionLogger do
end
context "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 do
describe "#log_remove_user_from_group" do
context "as group owner" do
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
@@ -77,12 +77,12 @@ RSpec.describe GroupActionLogger do
end
context "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 do
it "should create the right record" do
group.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.last

View File

@@ -1,6 +1,10 @@
# frozen_string_literal: true
RSpec.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 do
before { 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" do
before { GroupMessage.any_instance.stubs(:sent_recently?).returns(false) }
@@ -42,14 +42,17 @@ RSpec.describe GroupMessage do
end
describe "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" do
PostCreator.expects(:create).never
subject
group_message
end
end
@@ -57,29 +60,35 @@ RSpec.describe GroupMessage do
let(:user) { Fabricate.build(:user, id: 123_123) }
shared_examples "common message params for group messages" do
it "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_present
end
end
context "with user_automatically_silenced" do
subject do
subject(:message_params) do
GroupMessage.new(moderators_group, :user_automatically_silenced, user: user).message_params
end
include_examples "common message params for group messages"
end
context "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"
end
end
describe "methods that use redis" do
let(:user) { Fabricate.build(:user, id: 123_123) }
subject(:group_message) do
GroupMessage.new(moderators_group, :user_automatically_silenced, user: user)
end
let(:user) { Fabricate.build(:user, id: 123_123) }
before do
PostCreator.stubs(:create).returns(stub_everything)
group_message.stubs(:sent_recently_key).returns("the_key")

View File

@@ -1,15 +1,16 @@
# frozen_string_literal: true
RSpec.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) do
Fabricate(:tag, name: "great-books", staff_topic_count: 22, public_topic_count: 22)
end
fab!(: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 do
describe "#search" do
it "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"],
)
end
it "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"],
)
end
it "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"])
end
it "does not allow more than SEARCH_MAX_LIMIT results to be specified by the limit param" do
stub_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 do
it "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 first
DiscourseTagging.expects(:filter_allowed_tags).never
subject.search("the-book", %w[category tag], limit: 1)
service.search("the-book", %w[category tag], limit: 1)
end
it "includes the tag count" do
tag1.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"],
)
end
it "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"],
)
end
it "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"])
end
it "does not include categories the user cannot access" do
category1.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"])
end
it "does not include tags the user cannot access" do
Fabricate(: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_empty
end
it "includes other data sources" do
@@ -109,7 +110,7 @@ RSpec.describe HashtagAutocompleteService do
stub(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 do
it "handles refs for categories that have a parent" do
parent = 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 do
it "appends type suffixes for the ref on conflicting slugs on items that are not the top priority type" do
Fabricate(: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 do
stub(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 do
stub(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 do
stub(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 do
Fabricate(: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 do
fab!(: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],
)
end
it "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 do
before { 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"])
end
end
@@ -274,7 +275,7 @@ RSpec.describe HashtagAutocompleteService do
category1.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 do
fab!(: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 do
it "does not include categories the user cannot access" do
category1.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({})
end
it "does not include tags the user cannot access" do
Fabricate(: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" })
end
it "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 do
before { 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 do
fab!(: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 do
it "does not include category the user cannot access" do
category1.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([])
end
it "does not include tag the user cannot access" do
Fabricate(: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"])
end
it "handles type suffixes for slugs" do
result =
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 do
it "handles parent:child category lookups" do
parent_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 do
it "handles parent:child category lookups with type suffix" do
parent_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 do
it "does not return the category if the parent does not match the child" do
parent_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_empty
end
it "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 do
category1.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 do
stub(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"])
end
it "handles type suffix lookups where there is another type with a conflicting slug that the user cannot access" do
category1.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 do
before { 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([])

View File

@@ -1,6 +1,8 @@
# frozen_string_literal: true
RSpec.describe Notifications::ConsolidationPlanner do
subject(:planner) { described_class.new }
describe "#consolidate_or_save!" do
let(:threshold) { 1 }
fab!(:user) { Fabricate(:user) }
@@ -11,7 +13,7 @@ RSpec.describe Notifications::ConsolidationPlanner do
it "does nothing it haven't passed the consolidation threshold yet" do
notification = 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_present
expect(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 do
end
def plan_for(notification)
subject.plan_for(notification)
planner.plan_for(notification)
end
end

View File

@@ -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 do
let!(: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" do
it "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],
)
end
it "does not return bookmarks for posts where the user does not have access to the topic category" do
bookmark1.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],
)
end
it "does not return bookmarks for posts where the user does not have access to the private message" do
bookmark1.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],
)
end
end
@@ -43,8 +48,8 @@ RSpec.describe PostBookmarkable do
it "returns bookmarks that match by name" do
ts_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 do
ts_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 do
ts_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 do
ts_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 do
describe "#can_send_reminder?" do
it "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.reload
bookmark1.bookmarkable.topic.trash!
bookmark1.reload
expect(subject.can_send_reminder?(bookmark1)).to eq(false)
expect(registered_bookmarkable.can_send_reminder?(bookmark1)).to eq(false)
end
end
describe "#reminder_handler" do
it "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.last
expect(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 do
describe "#can_see?" do
it "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)
end
end
end

View File

@@ -171,6 +171,15 @@ RSpec.describe PostOwnerChanger do
end
context "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 do
UserActionManager.enable
end
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" do
PostActionCreator.like(p2user, p1)
expect(p1user.user_stat.reload.likes_received).to eq(1)

View File

@@ -15,10 +15,10 @@ RSpec.describe StaffActionLogger do
end
describe "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" do
expect { logger.log_user_deletion(nil) }.to raise_error(Discourse::InvalidParameters)
end
@@ -47,10 +47,10 @@ RSpec.describe StaffActionLogger do
end
describe "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" do
expect { logger.log_post_deletion(nil) }.to raise_error(Discourse::InvalidParameters)
end
@@ -116,14 +116,15 @@ RSpec.describe StaffActionLogger do
end
describe "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) do
described_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" do
expect {
logger.log_trust_level_change(nil, old_trust_level, new_trust_level)
@@ -371,11 +372,11 @@ RSpec.describe StaffActionLogger do
end
describe "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" do
log_record = logger.log_roll_up(subnet, ips)
expect(log_record).to be_valid
@@ -584,12 +585,12 @@ RSpec.describe StaffActionLogger do
end
describe "log_check_personal_message" do
fab!(:personal_message) { Fabricate(:private_message_topic) }
subject(:log_check_personal_message) do
described_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" do
expect { logger.log_check_personal_message(nil) }.to raise_error(Discourse::InvalidParameters)
end
@@ -604,10 +605,10 @@ RSpec.describe StaffActionLogger do
end
describe "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" do
expect { logger.log_post_approved(nil) }.to raise_error(Discourse::InvalidParameters)
end
@@ -622,12 +623,12 @@ RSpec.describe StaffActionLogger do
end
describe "log_post_rejected" do
fab!(:reviewable) { Fabricate(:reviewable_queued_post) }
subject(:log_post_rejected) do
described_class.new(admin).log_post_rejected(reviewable, DateTime.now)
end
fab!(:reviewable) { Fabricate(:reviewable_queued_post) }
it "raises an error when reviewable not supplied" do
expect { logger.log_post_rejected(nil, DateTime.now) }.to raise_error(
Discourse::InvalidParameters,

View File

@@ -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 do
let!(: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" do
it "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],
)
end
it "does not return bookmarks for posts where the user does not have access to the topic category" do
bookmark1.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],
)
end
it "does not return bookmarks for posts where the user does not have access to the private message" do
bookmark1.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],
)
end
end
@@ -44,8 +49,8 @@ RSpec.describe TopicBookmarkable do
it "returns bookmarks that match by name" do
ts_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 do
ts_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 do
ts_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 do
ts_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 do
describe "#can_send_reminder?" do
it "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)
end
end
describe "#reminder_handler" do
it "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.last
expect(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 do
describe "#can_see?" do
it "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)
end
end
end

View File

@@ -4,11 +4,12 @@ RSpec.describe UserAnonymizer do
let(:admin) { Fabricate(:admin) }
describe "event" do
let(:user) { Fabricate(:user, username: "edward") }
subject(:make_anonymous) do
described_class.make_anonymous(user, admin, anonymize_ip: "2.2.2.2")
end
let(:user) { Fabricate(:user, username: "edward") }
it "triggers the event" do
events = DiscourseEvent.track_events { make_anonymous }
@@ -22,10 +23,11 @@ RSpec.describe UserAnonymizer do
end
describe ".make_anonymous" do
subject(:make_anonymous) { described_class.make_anonymous(user, admin) }
let(:original_email) { "edward@example.net" }
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" do
make_anonymous

View File

@@ -75,9 +75,10 @@ RSpec.describe UserDestroyer do
end
context "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 do
context "when delete_posts is false" do
subject(:destroy) { UserDestroyer.new(admin).destroy(user) }
before do
user.stubs(:post_count).returns(1)
user.stubs(:first_post_created_at).returns(Time.zone.now)
@@ -253,18 +255,21 @@ RSpec.describe UserDestroyer do
end
context "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 UserDestroyer
user.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"
end
context "when user has deleted posts" do
let!(: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" do
expect { 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 do
context "when user has no posts" do
context "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"
end

View File

@@ -6,9 +6,10 @@ RSpec.describe UserSilencer do
fab!(: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" do
expect { UserSilencer.silence(user, admin) }.to change { user.reload.silenced? }