Skip to content

A platform for community discussion. Free, open, simple.

DEV: Prefer RSpec primitives for test setup (#42122)

Alan Guo Xiang Tan6df9b0b35700
diff --git a/.skills/discourse-writing-rspec-tests/SKILL.md b/.skills/discourse-writing-rspec-tests/SKILL.md
index 17903c89fbd..ea9a021b73b 100644
--- a/.skills/discourse-writing-rspec-tests/SKILL.md
+++ b/.skills/discourse-writing-rspec-tests/SKILL.md
@@ -16,6 +16,7 @@ Discourse uses RSpec for testing. Follow these patterns for all test types.
- **Don't assert that internal methods are or aren't called** — assertions like `SomeService.expects(:some_method).never` (or `.once`, `.with(...)`) couple the test to internal implementation details that the caller shouldn't care about. Assert on the observable outcome instead: returned value, persisted state, emitted event, response body, rendered output. If the implementation is later refactored, inlined, or renamed, a behavior-focused test still passes when the behavior is correct.
- **Capture infrastructure side effects without mocking internals** — use `DiscourseEvent.track_events` and `MessageBus.track_publish` when asserting emitted events or published messages instead of expecting calls to `trigger` or `publish`.
- **Prefer readability over DRYness** — tests are documentation. Some duplication is fine. Avoid deep `shared_examples`/`let` chains that hurt readability.
+- **Choose the smallest fitting test primitive** — use `fab!` for records shared across examples, `let` for lazy per-example values, `let!` when a per-example record must exist before the action, and `subject` for the operation under test. Use inline `Fabricate` for a record local to one example. Because `fab!` uses TestProf `let_it_be`, it cannot depend on `let` or other per-example setup. Keep `let` value-oriented rather than hiding a parameterized helper in a Proc or lambda. When parameterized behavior needs a name to keep one spec readable, define a small method in that example group; do not introduce one merely to wrap a simple `Fabricate`, `create!`, or direct call. Move the method into a focused, auto-loaded `spec/support` module only when it is shared by multiple spec files. Search `spec/fabricators` before creating setup by hand, and define a derived fabricator for a recurring record shape.
- **Test edge cases** — nil inputs, empty collections, boundary values, permission failures — not just happy paths.
- **Keep tests independent** — no test should depend on another test's execution or shared mutable state.
- **Verify placement in parent context** — before adding a new test, always read the surrounding `describe`/`context` block to confirm the test belongs there. Check that the parent context's description, `let`/`fab!` setup, and `before` hooks match the scenario being tested. A misplaced test inherits the wrong setup and produces misleading results.
@@ -29,31 +30,6 @@ Discourse uses RSpec for testing. Follow these patterns for all test types.
- **Limit nesting to 2 levels** — avoid more than 2 levels of `describe`/`context` nesting. Instead of deeply nested contexts, put the full scenario description in the `it` block itself. Flat tests are easier to read and maintain.
- **Avoid double negatives in descriptions** — write test descriptions that state the positive condition. For example, prefer `"returns true when topic_approval_type is approval or pre_approval"` over `"returns true when topic_approval_type is not none"`. Be specific about the values being tested.
-## Test Data with Fabricators
-
-Use `fab!` for shared test data, or `Fabricate` inline within the test example:
-
-```rb
-fab!(:user)
-fab!(:category)
-fab!(:tag)
-fab!(:topic) { Fabricate(:topic, category: category, tags: [tag]) }
-
-it "displays the topic" do
- sign_in(user)
- visit("/")
-end
-
-it "creates a new topic" do
- new_category = Fabricate(:category, name: "Special")
- # ... test using new_category
-end
-```
-
-Never use `before` blocks for Fabricate calls. Use `let!` only when absolutely necessary.
-
-Fabricators live in `spec/fabricators/` in core and each plugin. Search for an existing fabricator before hand-rolling setup. Name shared data for the role it plays (`fab!(:topic_creator)`, not `fab!(:user)`). For recurring non-default data, define a derived fabricator (`Fabricator(:variant, from: :base)`) named for its data state rather than adding a scenario-specific helper.
-
## Test Efficiency
Tests have setup overhead. **Optimize for the fewest test examples possible:**
diff --git a/plugins/automation/spec/fabricators/automation_stat_fabricator.rb b/plugins/automation/spec/fabricators/automation_stat_fabricator.rb
new file mode 100644
index 00000000000..05488bbd088
--- /dev/null
+++ b/plugins/automation/spec/fabricators/automation_stat_fabricator.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+Fabricator(:automation_stat, from: DiscourseAutomation::Stat) do
+ date { Date.current }
+ last_run_at { |attributes| attributes[:date].to_time + 10.hours }
+ total_time 1.0
+ average_run_time 1.0
+ min_run_time 1.0
+ max_run_time 1.0
+ total_runs 1
+ total_errors 0
+end
diff --git a/plugins/automation/spec/lib/discourse_automation/statistics_spec.rb b/plugins/automation/spec/lib/discourse_automation/statistics_spec.rb
index fc068c77d32..ff1b4f81096 100644
--- a/plugins/automation/spec/lib/discourse_automation/statistics_spec.rb
+++ b/plugins/automation/spec/lib/discourse_automation/statistics_spec.rb
@@ -3,20 +3,6 @@
RSpec.describe DiscourseAutomation::Statistics do
before { freeze_time(Time.utc(2026, 6, 15, 12, 0)) }
- def create_stat(automation_id, date:, runs: 1)
- DiscourseAutomation::Stat.create!(
- automation_id: automation_id,
- date: date,
- last_run_at: date.to_time + 10.hours,
- total_time: 1.0,
- average_run_time: 1.0,
- min_run_time: 1.0,
- max_run_time: 1.0,
- total_runs: runs,
- total_errors: 0,
- )
- end
-
describe ".total" do
it "counts every automation" do
Fabricate(:automation)
@@ -62,11 +48,17 @@ RSpec.describe DiscourseAutomation::Statistics do
end
describe ".executed" do
- it "counts distinct automations with runs in each window" do
- create_stat(1, date: Date.current, runs: 3)
- create_stat(1, date: 10.days.ago.to_date, runs: 2)
- create_stat(2, date: 45.days.ago.to_date, runs: 5)
+ fab!(:current_automation_stat) do
+ Fabricate(:automation_stat, automation_id: 1, date: Date.new(2026, 6, 15), total_runs: 3)
+ end
+ fab!(:recent_automation_stat) do
+ Fabricate(:automation_stat, automation_id: 1, date: Date.new(2026, 6, 5), total_runs: 2)
+ end
+ fab!(:previous_automation_stat) do
+ Fabricate(:automation_stat, automation_id: 2, date: Date.new(2026, 5, 1), total_runs: 5)
+ end
+ it "counts distinct automations with runs in each window" do
expect(described_class.executed).to eq(
last_day: 1,
"7_days": 1,
@@ -77,11 +69,17 @@ RSpec.describe DiscourseAutomation::Statistics do
end
describe ".executions" do
- it "sums runs in each window plus a lifetime count" do
- create_stat(1, date: Date.current, runs: 3)
- create_stat(1, date: 10.days.ago.to_date, runs: 2)
- create_stat(1, date: 45.days.ago.to_date, runs: 5)
+ fab!(:current_automation_stat) do
+ Fabricate(:automation_stat, automation_id: 1, date: Date.new(2026, 6, 15), total_runs: 3)
+ end
+ fab!(:recent_automation_stat) do
+ Fabricate(:automation_stat, automation_id: 1, date: Date.new(2026, 6, 5), total_runs: 2)
+ end
+ fab!(:previous_automation_stat) do
+ Fabricate(:automation_stat, automation_id: 1, date: Date.new(2026, 5, 1), total_runs: 5)
+ end
+ it "sums runs in each window plus a lifetime count" do
expect(described_class.executions).to eq(
last_day: 3,
"7_days": 3,
diff --git a/plugins/automation/spec/scripts/append_last_checked_by_spec.rb b/plugins/automation/spec/scripts/append_last_checked_by_spec.rb
index a9f5c4f3ba7..68ce8bf4436 100644
--- a/plugins/automation/spec/scripts/append_last_checked_by_spec.rb
+++ b/plugins/automation/spec/scripts/append_last_checked_by_spec.rb
@@ -8,25 +8,15 @@ describe "AppendLastCheckedBy" do
Fabricate(:automation, script: DiscourseAutomation::Scripts::APPEND_LAST_CHECKED_BY)
end
- def trigger_automation(post)
- cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
- checked_at = post.updated_at + 1.hour
- date_time = checked_at.strftime("%Y-%m-%dT%H:%M:%SZ")
- [cooked, checked_at, date_time]
- end
-
- def text(key)
- I18n.t("discourse_automation.scriptables.append_last_checked_by.#{key}")
- end
-
describe "#trigger!" do
it "works for newly created post" do
- cooked, checked_at, date_time = trigger_automation(post)
+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
+ translation_key = "discourse_automation.scriptables.append_last_checked_by"
expect(cooked.include?("<blockquote class=\"discourse-automation\">")).to be_truthy
expect(
cooked.include?(
- "<details><summary>#{text("summary")}</summary>#{text("details")}<input type=\"button\" value=\"#{text("button_text")}\" class=\"btn btn-checked\"></details>",
+ "<details><summary>#{I18n.t("#{translation_key}.summary")}</summary>#{I18n.t("#{translation_key}.details")}<input type=\"button\" value=\"#{I18n.t("#{translation_key}.button_text")}\" class=\"btn btn-checked\"></details>",
),
).to be_truthy
end
@@ -37,7 +27,8 @@ describe "AppendLastCheckedBy" do
topic.custom_fields[DiscourseAutomation::TOPIC_LAST_CHECKED_AT] = post.updated_at + 1.hour
topic.save_custom_fields
- cooked, checked_at = trigger_automation(post)
+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
+ checked_at = post.updated_at + 1.hour
expect(
cooked.include?(
diff --git a/plugins/automation/spec/scripts/append_last_edited_by_spec.rb b/plugins/automation/spec/scripts/append_last_edited_by_spec.rb
index c6b84cd6449..ab5360f8b95 100644
--- a/plugins/automation/spec/scripts/append_last_edited_by_spec.rb
+++ b/plugins/automation/spec/scripts/append_last_edited_by_spec.rb
@@ -8,18 +8,12 @@ describe "AppendLastEditedBy" do
Fabricate(:automation, script: DiscourseAutomation::Scripts::APPEND_LAST_EDITED_BY)
end
- def trigger_automation(post)
- cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
- updated_at = post.updated_at
- date_time = updated_at.strftime("%Y-%m-%dT%H:%M:%SZ")
- [cooked, updated_at]
- end
-
describe "#trigger!" do
it "works for newly created post" do
freeze_time
- cooked, updated_at = trigger_automation(post)
+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
+ updated_at = post.updated_at
expect(
cooked.include?(
PrettyText.cook(
@@ -37,7 +31,8 @@ describe "AppendLastEditedBy" do
it "works for existing post with last edited by detail" do
freeze_time
- cooked, updated_at = trigger_automation(post)
+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
+ updated_at = post.updated_at
expect(
cooked.include?(
PrettyText.cook(
@@ -53,7 +48,9 @@ describe "AppendLastEditedBy" do
PostRevisor.new(post).revise!(moderator, raw: "this is a post with edit")
- cooked, updated_at = trigger_automation(post.reload)
+ post.reload
+ cooked = automation.trigger!("post" => post, "cooked" => post.cooked)
+ updated_at = post.updated_at
expect(
cooked.include?(
PrettyText.cook(
diff --git a/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb b/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb
index a330508079b..b79cb8ef04c 100644
--- a/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb
+++ b/plugins/automation/spec/scripts/user_group_membership_through_badge_spec.rb
@@ -19,13 +19,8 @@ describe "UserGroupMembershipThroughBadge" do
BadgeGranter.clear_queue!
end
- def target_group_member?(user_ids)
- GroupUser.exists?(group_id: target_group.id, user_id: user_ids)
- end
-
- def owns_badge?(user_ids)
- UserBadge.exists?(user_id: user_ids, badge_id: badge.id)
- end
+ let(:target_group_memberships) { GroupUser.where(group_id: target_group.id) }
+ let(:badge_grants) { UserBadge.where(badge_id: badge.id) }
context "with invalid field values" do
let(:fake_logger) { FakeLogger.new }
@@ -86,7 +81,7 @@ describe "UserGroupMembershipThroughBadge" do
before { BadgeGranter.grant(badge, user) }
it "adds user to group" do
- expect(target_group_member?([user.id])).to eq(false)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(false)
expect do
automation.trigger!(
@@ -95,8 +90,8 @@ describe "UserGroupMembershipThroughBadge" do
)
end.to change { target_group.users.count }.by(1)
- expect(target_group_member?([user.id])).to eq(true)
- expect(owns_badge?([user.id])).to eq(true)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(true)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(true)
end
it "does nothing if user is an existing group member" do
@@ -116,7 +111,7 @@ describe "UserGroupMembershipThroughBadge" do
expect(GroupUser.find_by(group_id: target_group.id, user_id: user.id)).to eq(
current_membership,
)
- expect(owns_badge?([user.id])).to eq(true)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(true)
end
it "does not add other badge owners" do
@@ -132,15 +127,15 @@ describe "UserGroupMembershipThroughBadge" do
)
end.to change { target_group.reload.users.count }.by(1)
- expect(target_group_member?([user.id])).to eq(true)
- expect(owns_badge?([user.id])).to eq(true)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(true)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(true)
end
end
context "when user does not have badge" do
it "does not add user to group" do
- expect(target_group_member?([user.id])).to eq(false)
- expect(owns_badge?([user.id])).to eq(false)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(false)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(false)
expect do
automation.trigger!(
@@ -149,8 +144,8 @@ describe "UserGroupMembershipThroughBadge" do
)
end.not_to change { target_group.users.count }
- expect(target_group_member?([user.id])).to eq(false)
- expect(owns_badge?([user.id])).to eq(false)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(false)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(false)
end
it "does not add other badge owners" do
@@ -166,8 +161,8 @@ describe "UserGroupMembershipThroughBadge" do
)
end.not_to change { target_group.reload.users.count }
- expect(target_group_member?([user.id])).to eq(false)
- expect(owns_badge?([user.id])).to eq(false)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(false)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(false)
expect(target_group.users.count).to eq(0)
end
end
@@ -182,29 +177,29 @@ describe "UserGroupMembershipThroughBadge" do
before { badge_owners.each { |u| BadgeGranter.grant(badge, u) } }
it "adds all users with badge to group" do
- expect(target_group_member?(badge_owner_ids)).to eq(false)
- expect(target_group_member?(non_badge_owner_ids)).to eq(false)
+ expect(target_group_memberships.where(user_id: badge_owner_ids).exists?).to eq(false)
+ expect(target_group_memberships.where(user_id: non_badge_owner_ids).exists?).to eq(false)
expect do
automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)
end.to change { target_group.reload.users.count }.by(badge_owners.size)
- expect(target_group_member?(badge_owner_ids)).to eq(true)
- expect(target_group_member?(non_badge_owner_ids)).to eq(false)
+ expect(target_group_memberships.where(user_id: badge_owner_ids).exists?).to eq(true)
+ expect(target_group_memberships.where(user_id: non_badge_owner_ids).exists?).to eq(false)
end
it "skips existing group members with badge" do
badge_owners.each { |u| target_group.add(u) }
- expect(target_group_member?(badge_owner_ids)).to eq(true)
- expect(target_group_member?(non_badge_owner_ids)).to eq(false)
+ expect(target_group_memberships.where(user_id: badge_owner_ids).exists?).to eq(true)
+ expect(target_group_memberships.where(user_id: non_badge_owner_ids).exists?).to eq(false)
expect do
automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)
end.not_to change { target_group.reload.users.count }
- expect(target_group_member?(badge_owner_ids)).to eq(true)
- expect(target_group_member?(non_badge_owner_ids)).to eq(false)
+ expect(target_group_memberships.where(user_id: badge_owner_ids).exists?).to eq(true)
+ expect(target_group_memberships.where(user_id: non_badge_owner_ids).exists?).to eq(false)
end
end
@@ -220,32 +215,32 @@ describe "UserGroupMembershipThroughBadge" do
end
it "removes existing members without badge" do
- expect(target_group_member?(other_users.map(&:id))).to eq(true)
+ expect(target_group_memberships.where(user_id: other_users.map(&:id)).exists?).to eq(true)
expect do
automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)
end.to change { target_group.reload.users.count }.by(-other_users.count)
- expect(target_group_member?(other_users.map(&:id))).to eq(false)
+ expect(target_group_memberships.where(user_id: other_users.map(&:id)).exists?).to eq(false)
end
it "keeps existing members with badge" do
BadgeGranter.grant(badge, user)
target_group.add(user)
- expect(target_group_member?(other_users.map(&:id))).to eq(true)
- expect(owns_badge?(other_users.map(&:id))).to eq(false)
- expect(target_group_member?([user.id])).to eq(true)
- expect(owns_badge?([user.id])).to eq(true)
+ expect(target_group_memberships.where(user_id: other_users.map(&:id)).exists?).to eq(true)
+ expect(badge_grants.where(user_id: other_users.map(&:id)).exists?).to eq(false)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(true)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(true)
expect do
automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)
end.to change { target_group.reload.users.count }
- expect(target_group_member?(other_users.map(&:id))).to eq(false)
- expect(owns_badge?(other_users.map(&:id))).to eq(false)
- expect(target_group_member?([user.id])).to eq(true)
- expect(owns_badge?([user.id])).to eq(true)
+ expect(target_group_memberships.where(user_id: other_users.map(&:id)).exists?).to eq(false)
+ expect(badge_grants.where(user_id: other_users.map(&:id)).exists?).to eq(false)
+ expect(target_group_memberships.where(user_id: user.id).exists?).to eq(true)
+ expect(badge_grants.where(user_id: user.id).exists?).to eq(true)
end
end
@@ -262,15 +257,15 @@ describe "UserGroupMembershipThroughBadge" do
it "keeps existing members without badge" do
other_users.each { |u| target_group.add(u) }
- expect(target_group_member?(other_users.map(&:id))).to eq(true)
- expect(owns_badge?(other_users.map(&:id))).to eq(false)
+ expect(target_group_memberships.where(user_id: other_users.map(&:id)).exists?).to eq(true)
+ expect(badge_grants.where(user_id: other_users.map(&:id)).exists?).to eq(false)
expect do
automation.trigger!("kind" => DiscourseAutomation::Triggers::RECURRING)
end.not_to change { target_group.reload.users.count }
- expect(target_group_member?(other_users.map(&:id))).to eq(true)
- expect(owns_badge?(other_users.map(&:id))).to eq(false)
+ expect(target_group_memberships.where(user_id: other_users.map(&:id)).exists?).to eq(true)
+ expect(badge_grants.where(user_id: other_users.map(&:id)).exists?).to eq(false)
end
end
diff --git a/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rb b/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rb
index 608fab193d9..46cb5b76bfe 100644
--- a/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rb
+++ b/plugins/automation/spec/services/discourse_automation/action/log_automation_update_spec.rb
@@ -7,26 +7,30 @@ RSpec.describe DiscourseAutomation::Action::LogAutomationUpdate do
let(:guardian) { admin.guardian }
let(:empty_value) { I18n.t("discourse_automation.staff_action_logs.empty_value") }
- def call(previous_overrides = {})
- previous = {
+ let(:previous_automation_attributes) do
+ {
name: automation.name,
script: automation.script,
trigger: automation.trigger,
enabled: automation.enabled,
fields: automation.serialized_fields,
- }.merge(previous_overrides)
-
- described_class.call(automation, previous, guardian)
+ }
end
it "does not log when nothing changed" do
- expect { call }.not_to change { UserHistory.count }
+ expect {
+ described_class.call(automation, previous_automation_attributes, guardian)
+ }.not_to change { UserHistory.count }
end
it "logs attribute changes with automation id" do
automation.update!(name: "New Name", enabled: false)
- expect { call(name: "Old Name", enabled: true) }.to change { UserHistory.count }.by(1)
+ previous = previous_automation_attributes.merge(name: "Old Name", enabled: true)
+
+ expect { described_class.call(automation, previous, guardian) }.to change {
+ UserHistory.count
+ }.by(1)
expect(UserHistory.last).to have_attributes(
custom_type: "update_automation",
details:
@@ -40,11 +44,15 @@ RSpec.describe DiscourseAutomation::Action::LogAutomationUpdate do
it "formats empty values" do
automation.update!(name: "New Name")
- call(name: nil)
+ described_class.call(automation, previous_automation_attributes.merge(name: nil), guardian)
expect(UserHistory.last.details).to include("name: #{empty_value} → New Name")
automation.update!(name: "")
- call(name: "Old Name")
+ described_class.call(
+ automation,
+ previous_automation_attributes.merge(name: "Old Name"),
+ guardian,
+ )
expect(UserHistory.last.details).to include("name: Old Name → #{empty_value}")
end
@@ -63,7 +71,18 @@ RSpec.describe DiscourseAutomation::Action::LogAutomationUpdate do
{ "value" => new_time },
target: "trigger",
)
- call(fields: { "execute_at" => { "value" => original_time, "target" => "trigger" } })
+ described_class.call(
+ automation,
+ previous_automation_attributes.merge(
+ fields: {
+ "execute_at" => {
+ "value" => original_time,
+ "target" => "trigger",
+ },
+ },
+ ),
+ guardian,
+ )
expect(UserHistory.last.details).to include("execute_at: #{original_time} → #{new_time}")
end
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 3187a8e1dd2..a9ae6cfedf1 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -604,5 +604,3 @@ after_initialize do
DiscoursePluginRegistry.discourse_dev_populate_reviewable_types.add DiscourseDev::ReviewableMessage
end
end
-
-Dir[Rails.root.join("plugins/chat/spec/support/**/*.rb")].each { |f| require f } if Rails.env.test?
diff --git a/plugins/chat/spec/components/chat/mailer_spec.rb b/plugins/chat/spec/components/chat/mailer_spec.rb
index d858a5ec843..94354d2fd86 100644
--- a/plugins/chat/spec/components/chat/mailer_spec.rb
+++ b/plugins/chat/spec/components/chat/mailer_spec.rb
@@ -205,8 +205,7 @@ describe Chat::Mailer do
let!(:thread) do
Fabricate(:chat_thread, channel: followed_channel, original_message: chat_message)
end
-
- before do
+ let!(:thread_membership) do
Fabricate(
:user_chat_thread_membership,
user: user,
diff --git a/plugins/chat/spec/db/post_migrate/20260430172653_remove_duplicate_chat_mention_notifications_spec.rb b/plugins/chat/spec/db/post_migrate/20260430172653_remove_duplicate_chat_mention_notifications_spec.rb
deleted file mode 100644
index 05e21348884..00000000000
--- a/plugins/chat/spec/db/post_migrate/20260430172653_remove_duplicate_chat_mention_notifications_spec.rb
+++ /dev/null
@@ -1,138 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/chat/db/post_migrate/20260430172653_remove_duplicate_chat_mention_notifications.rb",
- )
-
-describe RemoveDuplicateChatMentionNotifications do
- fab!(:user_1, :user)
- fab!(:user_2, :user)
-
- before do
- @original_verbose = ActiveRecord::Migration.verbose
- ActiveRecord::Migration.verbose = false
- end
-
- after { ActiveRecord::Migration.verbose = @original_verbose }
-
- def insert_notification(
- user:,
- type: 29,
- data: '{"chat_message_id":1}',
- read: false,
- created_at: "2026-04-29 12:00:00"
- )
- DB.query_single(
- <<~SQL,
- INSERT INTO notifications (notification_type, user_id, data, read, high_priority, created_at, updated_at)
- VALUES (:type, :user_id, :data, :read, false, :created_at, :created_at)
- RETURNING id
- SQL
- user_id: user.id,
- type: type,
- data: data,
- read: read,
- created_at: created_at,
- ).first
- end
-
- def insert_mention_join(notification_id, chat_mention_id: 1)
- DB.exec(<<~SQL, notification_id: notification_id, chat_mention_id: chat_mention_id)
- INSERT INTO chat_mention_notifications (notification_id, chat_mention_id)
- VALUES (:notification_id, :chat_mention_id)
- SQL
- end
-
- def notification_ids_for(user)
- DB.query_single("SELECT id FROM notifications WHERE user_id = :id ORDER BY id", id: user.id)
- end
-
- def join_ids_for(notification_ids)
- DB.query_single(
- "SELECT notification_id FROM chat_mention_notifications WHERE notification_id IN (:ids) ORDER BY notification_id",
- ids: notification_ids,
- )
- end
-
- it "collapses duplicate chat_mention rows for the same user/data, keeping the oldest" do
- kept = insert_notification(user: user_1)
- dup_a = insert_notification(user: user_1)
- dup_b = insert_notification(user: user_1)
-
- described_class.new.up
-
- expect(notification_ids_for(user_1)).to eq([kept])
- end
-
- it "preserves distinct chat_mention rows (different data) for the same user" do
- a = insert_notification(user: user_1, data: '{"chat_message_id":1}')
- b = insert_notification(user: user_1, data: '{"chat_message_id":2}')
-
- described_class.new.up
-
- expect(notification_ids_for(user_1)).to contain_exactly(a, b)
- end
-
- it "marks the kept row read when any duplicate sibling was read" do
- kept = insert_notification(user: user_1, read: false)
- insert_notification(user: user_1, read: true)
-
- described_class.new.up
-
- read_state = DB.query_single("SELECT read FROM notifications WHERE id = :id", id: kept).first
- expect(read_state).to eq(true)
- end
-
- it "leaves the kept row read state unchanged when no sibling was read" do
- kept = insert_notification(user: user_1, read: false)
- insert_notification(user: user_1, read: false)
-
- described_class.new.up
-
- read_state = DB.query_single("SELECT read FROM notifications WHERE id = :id", id: kept).first
- expect(read_state).to eq(false)
- end
-
- it "deletes orphaned chat_mention_notifications join rows for removed duplicates" do
- kept = insert_notification(user: user_1)
- dup = insert_notification(user: user_1)
- insert_mention_join(kept, chat_mention_id: 100)
- insert_mention_join(dup, chat_mention_id: 100)
-
- described_class.new.up
-
- expect(join_ids_for([kept, dup])).to eq([kept])
- end
-
- it "ignores rows created before the deploy window" do
- a = insert_notification(user: user_1, created_at: "2026-04-28 23:59:00")
- b = insert_notification(user: user_1, created_at: "2026-04-28 23:59:30")
-
- described_class.new.up
-
- expect(notification_ids_for(user_1)).to contain_exactly(a, b)
- end
-
- it "ignores other notification types that share user/data shape" do
- chat_kept = insert_notification(user: user_1, type: 29)
- insert_notification(user: user_1, type: 29) # dup, should be removed
- other = insert_notification(user: user_1, type: 1) # mentioned, untouched
- other_dup = insert_notification(user: user_1, type: 1) # also untouched
-
- described_class.new.up
-
- expect(notification_ids_for(user_1)).to contain_exactly(chat_kept, other, other_dup)
- end
-
- it "dedupes independently for each affected user" do
- kept_1 = insert_notification(user: user_1)
- insert_notification(user: user_1)
- kept_2 = insert_notification(user: user_2)
- insert_notification(user: user_2)
-
- described_class.new.up
-
- expect(notification_ids_for(user_1)).to eq([kept_1])
- expect(notification_ids_for(user_2)).to eq([kept_2])
- end
-end
diff --git a/plugins/chat/spec/jobs/regular/chat/channel_archive_spec.rb b/plugins/chat/spec/jobs/regular/chat/channel_archive_spec.rb
index ecf6dbc3760..fecbd6a3402 100644
--- a/plugins/chat/spec/jobs/regular/chat/channel_archive_spec.rb
+++ b/plugins/chat/spec/jobs/regular/chat/channel_archive_spec.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
describe Jobs::Chat::ChannelArchive do
+ subject(:run_job) { described_class.new.execute(chat_channel_archive_id: chat_archive.id) }
+
fab!(:chat_channel, :category_channel)
fab!(:user) { Fabricate(:user, admin: true) }
fab!(:category)
@@ -16,10 +18,6 @@ describe Jobs::Chat::ChannelArchive do
before { 10.times { Fabricate(:chat_message, chat_channel: chat_channel) } }
- def run_job
- described_class.new.execute(chat_channel_archive_id: chat_archive.id)
- end
-
it "does nothing if the archive is already complete" do
chat_channel.chat_messages.destroy_all
chat_archive.update!(archived_messages: 10)
diff --git a/plugins/chat/spec/jobs/regular/chat/notify_watching_spec.rb b/plugins/chat/spec/jobs/regular/chat/notify_watching_spec.rb
index 1469c1def46..1a10d7d5565 100644
--- a/plugins/chat/spec/jobs/regular/chat/notify_watching_spec.rb
+++ b/plugins/chat/spec/jobs/regular/chat/notify_watching_spec.rb
@@ -5,28 +5,22 @@ RSpec.describe Jobs::Chat::NotifyWatching do
fab!(:user2, :user)
fab!(:user3, :user)
fab!(:group)
+ subject(:run_job) { described_class.new.execute(chat_message_id: message.id, except_user_ids:) }
+
let(:except_user_ids) { [] }
+ let(:notification_messages) do
+ MessageBus
+ .track_publish { run_job }
+ .filter do |published_message|
+ published_message.channel == "/chat/notification-alert/#{user2.id}"
+ end
+ end
before do
SiteSetting.chat_enabled = true
SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]
end
- def run_job(message)
- described_class.new.execute(chat_message_id: message.id, except_user_ids: except_user_ids)
- end
-
- def notification_messages_for(user, chat_message: message)
- MessageBus
- .track_publish { run_job(chat_message) }
- .filter { |m| m.channel == "/chat/notification-alert/#{user.id}" }
- end
-
- def track_core_notification(user:, message:, type: ::Notification.types[:chat_watched_thread])
- described_class.new.execute(chat_message_id: message.id)
- Notification.where(user: user, notification_type: type).last
- end
-
context "for a category channel" do
fab!(:channel, :category_channel)
fab!(:membership1) do
@@ -49,7 +43,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
end
it "sends a desktop notification" do
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages.first.data).to include(
{
@@ -88,14 +82,24 @@ RSpec.describe Jobs::Chat::NotifyWatching do
notification_level: Chat::NotificationLevels.all[:watching],
)
- notification = track_core_notification(user: user1, message: thread_message)
+ described_class.new.execute(chat_message_id: thread_message.id)
+ notification =
+ Notification.where(
+ user: user1,
+ notification_type: Notification.types[:chat_watched_thread],
+ ).last
expect(notification).to be_present
expect(notification.notification_type).to eq(Notification.types[:chat_watched_thread])
end
it "does not create a core notification when not watching the thread" do
- notification = track_core_notification(user: user1, message: thread_message)
+ described_class.new.execute(chat_message_id: thread_message.id)
+ notification =
+ Notification.where(
+ user: user1,
+ notification_type: Notification.types[:chat_watched_thread],
+ ).last
expect(notification).to be_nil
end
@@ -105,7 +109,12 @@ RSpec.describe Jobs::Chat::NotifyWatching do
notification_level: Chat::NotificationLevels.all[:watching],
)
membership1.update!(muted: true)
- notification = track_core_notification(user: user1, message: thread_message)
+ described_class.new.execute(chat_message_id: thread_message.id)
+ notification =
+ Notification.where(
+ user: user1,
+ notification_type: Notification.types[:chat_watched_thread],
+ ).last
expect(notification).to be_nil
end
@@ -125,22 +134,46 @@ RSpec.describe Jobs::Chat::NotifyWatching do
end
it "creates a core notification for watched threads" do
- expect { run_job(thread_message) }.to change { Notification.count }
+ expect {
+ described_class.new.execute(
+ chat_message_id: thread_message.id,
+ except_user_ids: except_user_ids,
+ )
+ }.to change { Notification.count }
end
it "does not create a core notification if channel is muted" do
membership1.update!(muted: true)
- expect { run_job(thread_message) }.not_to change { Notification.count }
+ expect {
+ described_class.new.execute(
+ chat_message_id: thread_message.id,
+ except_user_ids: except_user_ids,
+ )
+ }.not_to change { Notification.count }
end
it "does not create a desktop notification" do
- messages = notification_messages_for(user1)
+ messages =
+ MessageBus
+ .track_publish do
+ described_class.new.execute(
+ chat_message_id: message.id,
+ except_user_ids: except_user_ids,
+ )
+ end
+ .filter do |published_message|
+ published_message.channel == "/chat/notification-alert/#{user1.id}"
+ end
+
expect(messages).to be_empty
end
it "does not create a mobile notification" do
PostAlerter.expects(:push_notification).never
- run_job(thread_message)
+ described_class.new.execute(
+ chat_message_id: thread_message.id,
+ except_user_ids: except_user_ids,
+ )
end
end
end
@@ -156,7 +189,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
plugin_instance = Plugin::Instance.new
plugin_instance.register_modifier(:chat_notification_translation_args, &modifier_block)
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages.first.data[:translated_title]).to start_with("Hijacked")
ensure
@@ -174,7 +207,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
it "doesn't send notification alert via MessageBus" do
Plugin::Instance.new.register_push_notification_filter { |user, payload| false }
- expect(notification_messages_for(user2)).to be_empty
+ expect(notification_messages).to be_empty
end
end
@@ -183,7 +216,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
it "does not send a desktop or mobile notification" do
PostAlerter.expects(:push_notification).never
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages).to be_empty
end
end
@@ -213,7 +246,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
},
),
)
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages.length).to eq(1)
end
@@ -222,7 +255,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
it "does not send a desktop or mobile notification" do
PostAlerter.expects(:push_notification).never
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages).to be_empty
end
end
@@ -232,15 +265,17 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { SiteSetting.chat_allowed_groups = group.id }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
context "when the target user cannot see the chat channel" do
- before { channel.update!(chatable: Fabricate(:private_category, group: group)) }
+ fab!(:private_category) { Fabricate(:private_category, group: group) }
+
+ before { channel.update!(chatable: private_category) }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -248,7 +283,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { membership2.update!(last_read_message_id: message.id) }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -256,7 +291,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { user2.update!(suspended_till: 1.year.from_now) }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -264,7 +299,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
let(:except_user_ids) { [user2.id] }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
end
@@ -295,7 +330,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
end
it "sends a desktop notification" do
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages.first.data).to include(
{
@@ -322,7 +357,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
end
it "sends a desktop notification" do
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages.first.data).to include(
{
@@ -346,7 +381,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
it "does not send a desktop or mobile notification" do
PostAlerter.expects(:push_notification).never
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages).to be_empty
end
end
@@ -376,7 +411,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
},
),
)
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages.length).to eq(1)
end
@@ -385,7 +420,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
it "does not send a desktop or mobile notification" do
PostAlerter.expects(:push_notification).never
- messages = notification_messages_for(user2)
+ messages = notification_messages
expect(messages).to be_empty
end
end
@@ -395,7 +430,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { SiteSetting.chat_allowed_groups = group.id }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -403,7 +438,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { membership2.destroy! }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -411,7 +446,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { membership2.update!(last_read_message_id: message.id) }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -419,7 +454,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { user2.update!(suspended_till: 1.year.from_now) }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -427,7 +462,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
let(:except_user_ids) { [user2.id] }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
@@ -435,7 +470,7 @@ RSpec.describe Jobs::Chat::NotifyWatching do
before { UserCommScreener.any_instance.expects(:allowing_actor_communication).returns([]) }
it "does not send a desktop notification" do
- expect(notification_messages_for(user2).count).to be_zero
+ expect(notification_messages.count).to be_zero
end
end
end
diff --git a/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb b/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb
index 5f2482c14dc..6643236c87a 100644
--- a/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb
+++ b/plugins/chat/spec/lib/chat/channel_archive_service_spec.rb
@@ -13,7 +13,7 @@ describe Chat::ChannelArchiveService do
before { SiteSetting.chat_enabled = true }
describe "#create_archive_process" do
- before { 3.times { Fabricate(:chat_message, chat_channel: channel) } }
+ fab!(:channel_messages) { Fabricate.times(3, :chat_message, chat_channel: channel) }
it "marks the channel as read_only" do
described_class.create_archive_process(
@@ -84,25 +84,23 @@ describe Chat::ChannelArchiveService do
end
describe "#execute" do
- def create_messages(num)
- num.times { Fabricate(:chat_message, chat_channel: channel) }
+ def create_messages(count)
+ Fabricate.times(count, :chat_message, chat_channel: channel)
end
- def create_threaded_messages(num, title: nil)
+ def create_threaded_messages(count, title: nil)
original_message = Fabricate(:chat_message, chat_channel: channel)
- thread =
- Fabricate(:chat_thread, channel: channel, title: title, original_message: original_message)
- (num - 1).times { Fabricate(:chat_message, chat_channel: channel, thread: thread) }
- thread.update!(replies_count: num - 1)
+ thread = Fabricate(:chat_thread, channel:, title:, original_message:)
+ Fabricate.times(count - 1, :chat_message, chat_channel: channel, thread:)
+ thread.update!(replies_count: count - 1)
end
- def start_archive
- @channel_archive =
- described_class.create_archive_process(
- chat_channel: channel,
- acting_user: user,
- topic_params: topic_params,
- )
+ let(:channel_archive) do
+ described_class.create_archive_process(
+ chat_channel: channel,
+ acting_user: user,
+ topic_params: topic_params,
+ )
end
context "when archiving to a new topic" do
@@ -111,7 +109,8 @@ describe Chat::ChannelArchiveService do
end
it "makes a topic, deletes all the messages, creates posts for batches of messages, and changes the channel to archived" do
- create_messages(50) && start_archive
+ create_messages(50)
+ channel_archive
reaction_message = Chat::Message.last
Chat::MessageReaction.create!(
chat_message: reaction_message,
@@ -119,16 +118,16 @@ describe Chat::ChannelArchiveService do
emoji: "+1",
)
stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do
- described_class.new(@channel_archive).execute
+ described_class.new(channel_archive).execute
end
- @channel_archive.reload
- expect(@channel_archive.destination_topic.title).to eq("This will be a new topic")
- expect(@channel_archive.destination_topic.category).to eq(category)
- expect(@channel_archive.destination_topic.user).to eq(Discourse.system_user)
- expect(@channel_archive.destination_topic.tags.map(&:name)).to match_array(%w[news gossip])
+ channel_archive.reload
+ expect(channel_archive.destination_topic.title).to eq("This will be a new topic")
+ expect(channel_archive.destination_topic.category).to eq(category)
+ expect(channel_archive.destination_topic.user).to eq(Discourse.system_user)
+ expect(channel_archive.destination_topic.tags.map(&:name)).to match_array(%w[news gossip])
- topic = @channel_archive.destination_topic
+ topic = channel_archive.destination_topic
expect(topic.posts.count).to eq(11)
topic
.posts
@@ -144,9 +143,9 @@ describe Chat::ChannelArchiveService do
end
expect(topic.archived).to eq(true)
- expect(@channel_archive.archived_messages).to eq(50)
- expect(@channel_archive.chat_channel.status).to eq("archived")
- expect(@channel_archive.chat_channel.chat_messages.count).to eq(0)
+ expect(channel_archive.archived_messages).to eq(50)
+ expect(channel_archive.chat_channel.status).to eq("archived")
+ expect(channel_archive.chat_channel.chat_messages.count).to eq(0)
end
it "creates the correct posts for a channel with messages and threads" do
@@ -159,14 +158,14 @@ describe Chat::ChannelArchiveService do
create_threaded_messages(27, title: "another long thread")
create_messages(10)
- start_archive
+ channel_archive
stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do
- described_class.new(@channel_archive).execute
+ described_class.new(channel_archive).execute
end
- @channel_archive.reload
- topic = @channel_archive.destination_topic
+ channel_archive.reload
+ topic = channel_archive.destination_topic
expect(topic.posts.count).to eq(14)
topic
@@ -201,32 +200,35 @@ describe Chat::ChannelArchiveService do
end
expect(topic.archived).to eq(true)
- expect(@channel_archive.archived_messages).to eq(55)
- expect(@channel_archive.chat_channel.status).to eq("archived")
- expect(@channel_archive.chat_channel.chat_messages.count).to eq(0)
+ expect(channel_archive.archived_messages).to eq(55)
+ expect(channel_archive.chat_channel.status).to eq("archived")
+ expect(channel_archive.chat_channel.chat_messages.count).to eq(0)
end
it "does not stop the process if the post length is too high (validations disabled)" do
- create_messages(50) && start_archive
+ create_messages(50)
+ channel_archive
SiteSetting.max_post_length = 1
- described_class.new(@channel_archive).execute
- expect(@channel_archive.reload.complete?).to eq(true)
+ described_class.new(channel_archive).execute
+ expect(channel_archive.reload.complete?).to eq(true)
end
it "successfully links uploads from messages to the post" do
- create_messages(3) && start_archive
+ create_messages(3)
+ channel_archive
UploadReference.create!(target: Chat::Message.last, upload: Fabricate(:upload))
- described_class.new(@channel_archive).execute
- expect(@channel_archive.reload.complete?).to eq(true)
- expect(@channel_archive.destination_topic.posts.last.upload_references.count).to eq(1)
+ described_class.new(channel_archive).execute
+ expect(channel_archive.reload.complete?).to eq(true)
+ expect(channel_archive.destination_topic.posts.last.upload_references.count).to eq(1)
end
it "successfully sends a private message to the archiving user" do
- create_messages(3) && start_archive
- described_class.new(@channel_archive).execute
- expect(@channel_archive.reload.complete?).to eq(true)
+ create_messages(3)
+ channel_archive
+ described_class.new(channel_archive).execute
+ expect(channel_archive.reload.complete?).to eq(true)
pm_topic = Topic.private_messages.last
- expect(pm_topic.topic_allowed_users.first.user).to eq(@channel_archive.archived_by)
+ expect(pm_topic.topic_allowed_users.first.user).to eq(channel_archive.archived_by)
expect(pm_topic.title).to eq(
I18n.t("system_messages.chat_channel_archive_complete.subject_template"),
)
@@ -235,13 +237,14 @@ describe Chat::ChannelArchiveService do
it "does not continue archiving if the destination topic fails to be created" do
SiteSetting.max_emojis_in_title = 1
- create_messages(3) && start_archive
- @channel_archive.update!(destination_topic_title: "Wow this is the new title :tada: :joy:")
+ create_messages(3)
+ channel_archive
+ channel_archive.update!(destination_topic_title: "Wow this is the new title :tada: :joy:")
Discourse.expects(:warn_exception).once
- described_class.new(@channel_archive).execute
- expect(@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")
+ described_class.new(channel_archive).execute
+ expect(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")
pm_topic = Topic.private_messages.last
expect(pm_topic.title).to eq(
@@ -251,9 +254,10 @@ describe Chat::ChannelArchiveService do
end
it "uses the channel slug to autolink a hashtag for the channel in the PM" do
- create_messages(3) && start_archive
- described_class.new(@channel_archive).execute
- expect(@channel_archive.reload.complete?).to eq(true)
+ create_messages(3)
+ channel_archive
+ described_class.new(channel_archive).execute
+ expect(channel_archive.reload.complete?).to eq(true)
pm_topic = Topic.private_messages.last
expect(pm_topic.first_post.cooked).to have_tag(
"a",
@@ -290,9 +294,9 @@ describe Chat::ChannelArchiveService do
expect(
Chat::UserChatChannelMembership.where(chat_channel: channel, following: true).count,
).to eq(3)
- start_archive
- described_class.new(@channel_archive).execute
- expect(@channel_archive.reload.complete?).to eq(true)
+ channel_archive
+ described_class.new(channel_archive).execute
+ expect(channel_archive.reload.complete?).to eq(true)
expect(
Chat::UserChatChannelMembership.where(chat_channel: channel, following: true).count,
).to eq(0)
@@ -302,9 +306,9 @@ describe Chat::ChannelArchiveService do
Chat::UserChatChannelMembership.last.update!(
last_read_message_id: channel.chat_messages.first.id,
)
- start_archive
- described_class.new(@channel_archive).execute
- expect(@channel_archive.reload.complete?).to eq(true)
+ channel_archive
+ described_class.new(channel_archive).execute
+ expect(channel_archive.reload.complete?).to eq(true)
expect(Chat::UserChatChannelMembership.last.last_read_message_id).to eq(
channel.chat_messages.last.id,
)
@@ -316,9 +320,10 @@ describe Chat::ChannelArchiveService do
before { SiteSetting.chat_archive_destination_topic_status = "archived" }
it "archives the topic" do
- create_messages(3) && start_archive
- described_class.new(@channel_archive).execute
- topic = @channel_archive.destination_topic
+ create_messages(3)
+ channel_archive
+ described_class.new(channel_archive).execute
+ topic = channel_archive.destination_topic
topic.reload
expect(topic.archived).to eq(true)
end
@@ -328,9 +333,10 @@ describe Chat::ChannelArchiveService do
before { SiteSetting.chat_archive_destination_topic_status = "open" }
it "leaves the topic open" do
- create_messages(3) && start_archive
- described_class.new(@channel_archive).execute
- topic = @channel_archive.destination_topic
+ create_messages(3)
+ channel_archive
+ described_class.new(channel_archive).execute
+ topic = channel_archive.destination_topic
topic.reload
expect(topic.archived).to eq(false)
expect(topic.open?).to eq(true)
@@ -341,9 +347,10 @@ describe Chat::ChannelArchiveService do
before { SiteSetting.chat_archive_destination_topic_status = "closed" }
it "closes the topic" do
- create_messages(3) && start_archive
- described_class.new(@channel_archive).execute
- topic = @channel_archive.destination_topic
+ create_messages(3)
+ channel_archive
+ described_class.new(channel_archive).execute
+ topic = channel_archive.destination_topic
topic.reload
expect(topic.archived).to eq(false)
expect(topic.closed?).to eq(true)
@@ -352,13 +359,14 @@ describe Chat::ChannelArchiveService do
context "when archiving to an existing topic" do
it "does not change the status of the topic" do
- create_messages(3) && start_archive
- @channel_archive.update(
+ create_messages(3)
+ channel_archive
+ channel_archive.update(
destination_topic_title: nil,
destination_topic_id: Fabricate(:topic).id,
)
- described_class.new(@channel_archive).execute
- topic = @channel_archive.destination_topic
+ described_class.new(channel_archive).execute
+ topic = channel_archive.destination_topic
topic.reload
expect(topic.archived).to eq(false)
expect(topic.closed?).to eq(false)
@@ -369,12 +377,13 @@ describe Chat::ChannelArchiveService do
context "when archiving to an existing topic" do
fab!(:topic)
- let(:topic_params) { { topic_id: topic.id } }
+ fab!(:existing_topic_posts) { Fabricate.times(3, :post, topic:) }
- before { 3.times { Fabricate(:post, topic: topic) } }
+ let(:topic_params) { { topic_id: topic.id } }
it "deletes all the messages, creates posts for batches of messages, and changes the channel to archived" do
- create_messages(50) && start_archive
+ create_messages(50)
+ channel_archive
reaction_message = Chat::Message.last
Chat::MessageReaction.create!(
chat_message: reaction_message,
@@ -382,15 +391,15 @@ describe Chat::ChannelArchiveService do
emoji: "+1",
)
stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do
- described_class.new(@channel_archive).execute
+ described_class.new(channel_archive).execute
end
- @channel_archive.reload
- expect(@channel_archive.destination_topic.title).to eq(topic.title)
- expect(@channel_archive.destination_topic.category).to eq(topic.category)
- expect(@channel_archive.destination_topic.user).to eq(topic.user)
+ channel_archive.reload
+ expect(channel_archive.destination_topic.title).to eq(topic.title)
+ expect(channel_archive.destination_topic.category).to eq(topic.category)
+ expect(channel_archive.destination_topic.user).to eq(topic.user)
- topic = @channel_archive.destination_topic
+ topic = channel_archive.destination_topic
# existing posts + 10 archive posts
expect(topic.posts.count).to eq(13)
@@ -408,13 +417,14 @@ describe Chat::ChannelArchiveService do
end
expect(topic.archived).to eq(false)
- expect(@channel_archive.archived_messages).to eq(50)
- expect(@channel_archive.chat_channel.status).to eq("archived")
- expect(@channel_archive.chat_channel.chat_messages.count).to eq(0)
+ expect(channel_archive.archived_messages).to eq(50)
+ expect(channel_archive.chat_channel.status).to eq("archived")
+ expect(channel_archive.chat_channel.chat_messages.count).to eq(0)
end
it "handles errors gracefully, sends a private message to the archiving user, and is idempotent on retry" do
- create_messages(35) && start_archive
+ create_messages(35)
+ channel_archive
Chat::ChannelArchiveService
.any_instance
@@ -423,26 +433,26 @@ describe Chat::ChannelArchiveService do
Discourse.expects(:warn_exception).once
stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do
- expect { described_class.new(@channel_archive).execute }.to raise_error(FakeArchiveError)
+ expect { described_class.new(channel_archive).execute }.to raise_error(FakeArchiveError)
end
- expect(@channel_archive.reload.archive_error).to eq("this is a test error")
+ expect(channel_archive.reload.archive_error).to eq("this is a test error")
pm_topic = Topic.private_messages.last
- expect(pm_topic.topic_allowed_users.first.user).to eq(@channel_archive.archived_by)
+ expect(pm_topic.topic_allowed_users.first.user).to eq(channel_archive.archived_by)
expect(pm_topic.title).to eq(
I18n.t("system_messages.chat_channel_archive_failed.subject_template"),
)
Chat::ChannelArchiveService.any_instance.unstub(:create_post)
stub_const(Chat::ChannelArchiveService, "ARCHIVED_MESSAGES_PER_POST", 5) do
- described_class.new(@channel_archive).execute
+ described_class.new(channel_archive).execute
end
- @channel_archive.reload
- expect(@channel_archive.archive_error).to eq(nil)
- expect(@channel_archive.archived_messages).to eq(35)
- expect(@channel_archive.complete?).to eq(true)
+ channel_archive.reload
+ expect(channel_archive.archive_error).to eq(nil)
+ expect(channel_archive.archived_messages).to eq(35)
+ expect(channel_archive.complete?).to eq(true)
# existing posts + 7 archive posts
expect(topic.posts.count).to eq(10)
end
diff --git a/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb b/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb
index 7dd42f6e9dd..c060ddf3a25 100644
--- a/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb
+++ b/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb
@@ -12,13 +12,8 @@ describe Chat::ChannelFetcher do
fab!(:user1) { Fabricate(:user, group_ids: [chatters.id]) }
fab!(:user2, :user)
- def guardian
- Guardian.new(user1)
- end
-
- def memberships
- Chat::UserChatChannelMembership.where(user: user1)
- end
+ let(:guardian) { user1.guardian }
+ let(:memberships) { Chat::UserChatChannelMembership.where(user: user1) }
before { SiteSetting.chat_allowed_groups = chatters }
@@ -50,13 +45,15 @@ describe Chat::ChannelFetcher do
describe ".tracking_state" do
context "when user is member of the channel" do
- before do
+ fab!(:category_channel_membership) do
Fabricate(:user_chat_channel_membership, chat_channel: category_channel, user: user1)
end
context "with unread messages" do
- before do
+ fab!(:first_unread_message) do
Fabricate(:chat_message, chat_channel: category_channel, message: "hi", user: user2)
+ end
+ fab!(:second_unread_message) do
Fabricate(:chat_message, chat_channel: category_channel, message: "bonjour", user: user2)
end
@@ -92,7 +89,7 @@ describe Chat::ChannelFetcher do
context "when user is not member of the channel" do
context "when the channel has new messages" do
- before do
+ fab!(:new_channel_message) do
Fabricate(:chat_message, chat_channel: category_channel, message: "hi", user: user2)
end
diff --git a/plugins/chat/spec/lib/chat/statistics_spec.rb b/plugins/chat/spec/lib/chat/statistics_spec.rb
index f4d311231f3..4c3832b84fb 100644
--- a/plugins/chat/spec/lib/chat/statistics_spec.rb
+++ b/plugins/chat/spec/lib/chat/statistics_spec.rb
@@ -3,24 +3,22 @@
describe Chat::Statistics do
fab!(:frozen_time) { DateTime.parse("2022-07-08 09:30:00") }
- def minus_time(time)
- frozen_time - time
- end
-
fab!(:user1, :user)
fab!(:user2, :user)
fab!(:user3, :user)
fab!(:user4, :user)
fab!(:user5, :user)
- fab!(:channel1) { Fabricate(:chat_channel, created_at: minus_time(1.hour)) }
- fab!(:channel2) { Fabricate(:chat_channel, created_at: minus_time(2.days)) }
- fab!(:channel3) { Fabricate(:chat_channel, created_at: minus_time(6.days)) }
- fab!(:channel3) { Fabricate(:chat_channel, created_at: minus_time(20.days)) }
- fab!(:channel4) { Fabricate(:chat_channel, created_at: minus_time(21.days), status: :closed) }
- fab!(:channel5) { Fabricate(:chat_channel, created_at: minus_time(24.days)) }
- fab!(:channel6) { Fabricate(:chat_channel, created_at: minus_time(40.days)) }
- fab!(:channel7) { Fabricate(:chat_channel, created_at: minus_time(100.days), status: :archived) }
+ fab!(:channel1) { Fabricate(:chat_channel, created_at: frozen_time - 1.hour) }
+ fab!(:channel2) { Fabricate(:chat_channel, created_at: frozen_time - 2.days) }
+ fab!(:channel3) { Fabricate(:chat_channel, created_at: frozen_time - 6.days) }
+ fab!(:channel3) { Fabricate(:chat_channel, created_at: frozen_time - 20.days) }
+ fab!(:channel4) { Fabricate(:chat_channel, created_at: frozen_time - 21.days, status: :closed) }
+ fab!(:channel5) { Fabricate(:chat_channel, created_at: frozen_time - 24.days) }
+ fab!(:channel6) { Fabricate(:chat_channel, created_at: frozen_time - 40.days) }
+ fab!(:channel7) do
+ Fabricate(:chat_channel, created_at: frozen_time - 100.days, status: :archived)
+ end
fab!(:membership1) do
Fabricate(:user_chat_channel_membership, user: user1, chat_channel: channel1)
@@ -33,44 +31,49 @@ describe Chat::Statistics do
end
fab!(:message1) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(5.minutes), user: user1)
+ Fabricate(
+ :chat_message,
+ chat_channel: channel1,
+ created_at: frozen_time - 5.minutes,
+ user: user1,
+ )
end
fab!(:message2) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(2.days), user: user2)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 2.days, user: user2)
end
fab!(:message3) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(6.days), user: user2)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 6.days, user: user2)
end
fab!(:message4) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(11.days), user: user2)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 11.days, user: user2)
end
fab!(:message5) do
- Fabricate(:chat_message, chat_channel: channel4, created_at: minus_time(12.days), user: user3)
+ Fabricate(:chat_message, chat_channel: channel4, created_at: frozen_time - 12.days, user: user3)
end
fab!(:message6) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(13.days), user: user2)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 13.days, user: user2)
end
fab!(:message7) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(16.days), user: user1)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 16.days, user: user1)
end
fab!(:message8) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(42.days), user: user3)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 42.days, user: user3)
end
fab!(:message9) do
Fabricate(
:chat_message,
chat_channel: channel1,
- created_at: minus_time(42.days),
+ created_at: frozen_time - 42.days,
user: user3,
- deleted_at: minus_time(10.days),
+ deleted_at: frozen_time - 10.days,
deleted_by: user3,
)
end
fab!(:message10) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(50.days), user: user4)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 50.days, user: user4)
end
fab!(:message10) do
- Fabricate(:chat_message, chat_channel: channel1, created_at: minus_time(62.days), user: user4)
+ Fabricate(:chat_message, chat_channel: channel1, created_at: frozen_time - 62.days, user: user4)
end
before { freeze_time(DateTime.parse("2022-07-08 09:30:00")) }
diff --git a/plugins/chat/spec/requests/application_controller_spec.rb b/plugins/chat/spec/requests/application_controller_spec.rb
index f799fa48729..ccddcfaae65 100644
--- a/plugins/chat/spec/requests/application_controller_spec.rb
+++ b/plugins/chat/spec/requests/application_controller_spec.rb
@@ -4,7 +4,7 @@ RSpec.describe ApplicationController do
fab!(:user)
fab!(:admin)
- def preloaded_json
+ let(:preloaded_json) do
JSON.parse(Nokogiri::HTML5.fragment(response.body).css("script#data-preloaded").first.text)
end
diff --git a/plugins/chat/spec/requests/chat/api/channels_status_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_status_controller_spec.rb
index 9d1363fdc5a..b5555d6ee30 100644
--- a/plugins/chat/spec/requests/chat/api/channels_status_controller_spec.rb
+++ b/plugins/chat/spec/requests/chat/api/channels_status_controller_spec.rb
@@ -8,29 +8,29 @@ RSpec.describe Chat::Api::ChannelsStatusController do
SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]
end
- def status(status)
- { status: status }
- end
-
describe "#update" do
context "when user is not staff" do
- before { sign_in(Fabricate(:user)) }
+ fab!(:user)
+
+ before { sign_in(user) }
it "returns an error" do
- put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")
+ put "/chat/api/channels/#{channel_1.id}/status", params: { status: "closed" }
expect(response.status).to eq(403)
end
end
context "when user is admin" do
- before { sign_in(Fabricate(:admin)) }
+ fab!(:admin)
+
+ before { sign_in(admin) }
context "when channel doesn’t exist" do
before { channel_1.destroy! }
it "returns an error" do
- put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")
+ put "/chat/api/channels/#{channel_1.id}/status", params: { status: "closed" }
expect(response.status).to eq(404)
end
@@ -40,7 +40,7 @@ RSpec.describe Chat::Api::ChannelsStatusController do
before { channel_1.update!(status: "read_only") }
it "returns an error" do
- put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")
+ put "/chat/api/channels/#{channel_1.id}/status", params: { status: "closed" }
expect(response.status).to eq(403)
end
@@ -50,7 +50,7 @@ RSpec.describe Chat::Api::ChannelsStatusController do
before { channel_1.update!(status: "archived") }
it "returns an error" do
- put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")
+ put "/chat/api/channels/#{channel_1.id}/status", params: { status: "closed" }
expect(response.status).to eq(403)
end
@@ -59,7 +59,7 @@ RSpec.describe Chat::Api::ChannelsStatusController do
context "when changing from open to closed" do
it "changes the status" do
expect {
- put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")
+ put "/chat/api/channels/#{channel_1.id}/status", params: { status: "closed" }
}.to change { channel_1.reload.status }.to("closed").from("open")
expect(response.status).to eq(200)
@@ -73,7 +73,7 @@ RSpec.describe Chat::Api::ChannelsStatusController do
it "changes the status" do
expect {
- put "/chat/api/channels/#{channel_1.id}/status", params: status("open")
+ put "/chat/api/channels/#{channel_1.id}/status", params: { status: "open" }
}.to change { channel_1.reload.status }.to("open").from("closed")
expect(response.status).to eq(200)
diff --git a/plugins/chat/spec/system/kick_user_from_channel_spec.rb b/plugins/chat/spec/system/kick_user_from_channel_spec.rb
index c3143638a40..5c3cbd78390 100644
--- a/plugins/chat/spec/system/kick_user_from_channel_spec.rb
+++ b/plugins/chat/spec/system/kick_user_from_channel_spec.rb
@@ -18,16 +18,12 @@ describe "Kick user from chat channel" do
channel_2.add(current_user)
end
- def publish_kick
- Chat::Publisher.publish_kick_users(channel_1.id, [current_user.id])
- end
-
context "when the user is looking at the channel they are kicked from" do
before { chat.visit_channel(channel_1) }
context "when the user presses ok" do
it "redirects them to the first other public channel they have" do
- publish_kick
+ Chat::Publisher.publish_kick_users(channel_1.id, [current_user.id])
dialog.click_yes
expect(page).to have_current_path(channel_2.url)
end
@@ -39,7 +35,7 @@ describe "Kick user from chat channel" do
end
it "redirects them to the chat browse page" do
- publish_kick
+ Chat::Publisher.publish_kick_users(channel_1.id, [current_user.id])
dialog.click_yes
expect(page).to have_current_path("/chat/browse/open")
end
@@ -51,7 +47,7 @@ describe "Kick user from chat channel" do
before { chat.visit_channel(channel_2) }
it "removes it from their sidebar and does not redirect" do
- publish_kick
+ Chat::Publisher.publish_kick_users(channel_1.id, [current_user.id])
expect(sidebar_page.channels_section).to have_no_css(
".sidebar-section-link.channel-#{channel_1.id}",
)
diff --git a/plugins/chat/spec/system/user_profile_spec.rb b/plugins/chat/spec/system/user_profile_spec.rb
index 7399bbc4ee5..f6754ebd66c 100644
--- a/plugins/chat/spec/system/user_profile_spec.rb
+++ b/plugins/chat/spec/system/user_profile_spec.rb
@@ -21,16 +21,12 @@ RSpec.describe "User profile" do
end
end
- def visit_user_profile
- visit("/u/" + user.username + "/summary")
- end
-
context "when user" do
context "with chat disabled" do
before do
SiteSetting.chat_enabled = false
sign_in(current_user)
- visit_user_profile
+ visit("/u/#{user.username}/summary")
end
include_examples "not showing chat button"
@@ -39,7 +35,7 @@ RSpec.describe "User profile" do
context "with chat enabled" do
before do
sign_in(current_user)
- visit_user_profile
+ visit("/u/#{user.username}/summary")
end
include_examples "showing chat button"
@@ -47,7 +43,7 @@ RSpec.describe "User profile" do
end
context "when anonymous" do
- before { visit_user_profile }
+ before { visit("/u/#{user.username}/summary") }
include_examples "not showing chat button"
end
diff --git a/plugins/discourse-affiliate/spec/db/migrate/20250722101702_enable_affiliate_if_already_installed_spec.rb b/plugins/discourse-affiliate/spec/db/migrate/20250722101702_enable_affiliate_if_already_installed_spec.rb
deleted file mode 100644
index fffe45968e0..00000000000
--- a/plugins/discourse-affiliate/spec/db/migrate/20250722101702_enable_affiliate_if_already_installed_spec.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-# frozen_string_literal: true
-
-require_relative "../../../db/migrate/20250722101702_enable_affiliate_if_already_installed"
-
-RSpec.describe EnableAffiliateIfAlreadyInstalled do
- let(:connection) { ActiveRecord::Base.connection }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before do
- @provider = SiteSetting.provider
- SiteSetting.provider = SiteSettings::DbProvider.new(SiteSetting)
- end
-
- after { SiteSetting.provider = @provider }
-
- it "enables the affiliate plugin if it was previously installed" do
- expect(SiteSetting.affiliate_enabled).to eq(false)
- SiteSetting.affiliate_amazon_ca = "abc"
-
- EnableAffiliateIfAlreadyInstalled.new.up
-
- SiteSetting.refresh!
- expect(SiteSetting.affiliate_enabled).to eq(true)
- end
-
- it "leaves disabled if not configured" do
- expect(SiteSetting.affiliate_enabled).to eq(false)
-
- EnableAffiliateIfAlreadyInstalled.new.up
-
- SiteSetting.refresh!
- expect(SiteSetting.affiliate_enabled).to eq(false)
- end
-end
diff --git a/plugins/discourse-affiliate/spec/integration/content_localization_spec.rb b/plugins/discourse-affiliate/spec/integration/content_localization_spec.rb
index aacf43d1beb..6552f05dc04 100644
--- a/plugins/discourse-affiliate/spec/integration/content_localization_spec.rb
+++ b/plugins/discourse-affiliate/spec/integration/content_localization_spec.rb
@@ -6,6 +6,7 @@ describe "Affiliate links on localized posts" do
let(:amazon_url) { "https://www.amazon.de/gp/product/B0C3WGSSWC" }
let(:affiliate_tag) { "tag=discourse-21" }
+ let(:post_with_link) { create_post(raw: "Great deal at #{amazon_url}", user: admin).reload }
before do
enable_current_plugin
@@ -17,12 +18,8 @@ describe "Affiliate links on localized posts" do
SiteSetting.content_localization_allowed_groups = localizer_group.id.to_s
end
- def create_post_with_link
- create_post(raw: "Great deal at #{amazon_url}", user: admin).reload
- end
-
it "applies affiliate codes to a newly created localization" do
- post = create_post_with_link
+ post = post_with_link
localization =
PostLocalizationCreator.create(
@@ -37,7 +34,7 @@ describe "Affiliate links on localized posts" do
end
it "applies affiliate codes to an updated localization" do
- post = create_post_with_link
+ post = post_with_link
PostLocalizationCreator.create(post: post, locale: "ja", raw: "お得な情報", user: admin)
localization =
@@ -52,7 +49,7 @@ describe "Affiliate links on localized posts" do
end
it "applies affiliate codes to an existing localization when it is recooked" do
- post = create_post_with_link
+ post = post_with_link
localization =
PostLocalizationCreator.create(
post: post,
diff --git a/plugins/discourse-ai/spec/db/migrate/20241031041242_migrate_sentiment_classification_result_format_spec.rb b/plugins/discourse-ai/spec/db/migrate/20241031041242_migrate_sentiment_classification_result_format_spec.rb
deleted file mode 100644
index 9cf6051b8fc..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20241031041242_migrate_sentiment_classification_result_format_spec.rb
+++ /dev/null
@@ -1,56 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20241031041242_migrate_sentiment_classification_result_format",
- )
-
-RSpec.describe MigrateSentimentClassificationResultFormat do
- let(:connection) { ActiveRecord::Base.connection }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before do
- enable_current_plugin
- connection.execute(<<~SQL)
- INSERT INTO classification_results (model_used, classification, created_at, updated_at) VALUES
- ('sentiment', '{"neutral": 65, "negative": 20, "positive": 14}', NOW(), NOW()),
- ('emotion', '{"sadness": 10, "surprise": 15, "fear": 5, "anger": 20, "joy": 30, "disgust": 8, "neutral": 10}', NOW(), NOW());
- SQL
- end
-
- after { connection.execute("DELETE FROM classification_results") }
-
- describe "#up" do
- before { described_class.new.up }
-
- it "migrates sentiment classifications correctly" do
- sentiment_result = connection.execute(<<~SQL).first
- SELECT * FROM classification_results
- WHERE model_used = 'cardiffnlp/twitter-roberta-base-sentiment-latest';
- SQL
-
- expected_sentiment = { "neutral" => 0.65, "negative" => 0.20, "positive" => 0.14 }
-
- expect(JSON.parse(sentiment_result["classification"])).to eq(expected_sentiment)
- end
-
- it "migrates emotion classifications correctly" do
- emotion_result = connection.execute(<<~SQL).first
- SELECT * FROM classification_results
- WHERE model_used = 'j-hartmann/emotion-english-distilroberta-base';
- SQL
-
- expected_emotion = {
- "sadness" => 0.10,
- "surprise" => 0.15,
- "fear" => 0.05,
- "anger" => 0.20,
- "joy" => 0.30,
- "disgust" => 0.08,
- "neutral" => 0.10,
- }
-
- expect(JSON.parse(emotion_result["classification"])).to eq(expected_emotion)
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20250125162658_fix_broken_open_ai_embeddings_config_spec.rb b/plugins/discourse-ai/spec/db/migrate/20250125162658_fix_broken_open_ai_embeddings_config_spec.rb
deleted file mode 100644
index 29dc80a8f00..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20250125162658_fix_broken_open_ai_embeddings_config_spec.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20250125162658_fix_broken_open_ai_embeddings_config",
- )
-
-RSpec.describe FixBrokenOpenAiEmbeddingsConfig do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- def store_setting(name, val)
- connection.execute <<~SQL
- INSERT INTO site_settings(name, data_type, value, created_at, updated_at)
- VALUES ('#{name}', 3, '#{val}', NOW(), NOW())
- SQL
- end
-
- def configured_model_id
- DB.query_single(
- "SELECT value FROM site_settings WHERE name = 'ai_embeddings_selected_model'",
- ).first
- end
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before { enable_current_plugin }
-
- describe "#up" do
- context "when embeddings are already configured" do
- fab!(:embedding_definition)
-
- before { store_setting("ai_embeddings_selected_model", embedding_definition.id) }
-
- it "does nothing" do
- migration.up
-
- expect(configured_model_id).to eq(embedding_definition.id.to_s)
- end
- end
-
- context "when there is no previous config" do
- it "does nothing" do
- migration.up
-
- expect(configured_model_id).to be_blank
- end
- end
-
- context "when things are not fully configured" do
- before do
- store_setting("ai_embeddings_model", "text-embedding-3-large")
- store_setting("ai_openai_api_key", "")
- end
-
- it "does nothing" do
- migration.up
-
- expect(configured_model_id).to be_blank
- end
- end
-
- context "when we have a configuration that previously failed to copy" do
- before do
- store_setting("ai_embeddings_model", "text-embedding-3-large")
- store_setting("ai_openai_api_key", "123")
- end
-
- it "copies the config" do
- migration.up
-
- embedding_def = EmbeddingDefinition.last
-
- expect(configured_model_id).to eq(embedding_def.id.to_s)
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20250127145305_clean_unused_embedding_search_indexes_spec.rb b/plugins/discourse-ai/spec/db/migrate/20250127145305_clean_unused_embedding_search_indexes_spec.rb
deleted file mode 100644
index 76c32801bed..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20250127145305_clean_unused_embedding_search_indexes_spec.rb
+++ /dev/null
@@ -1,141 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20250127145305_clean_unused_embedding_search_indexes",
- )
-
-RSpec.describe CleanUnusedEmbeddingSearchIndexes do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before { enable_current_plugin }
-
- describe "#up" do
- before do
- # Copied from 20241008054440_create_binary_indexes_for_embeddings
- %w[topics posts document_fragments].each do |type|
- # our supported embeddings models IDs and dimensions
- [
- [1, 768],
- [2, 1536],
- [3, 1024],
- [4, 1024],
- [5, 768],
- [6, 1536],
- [7, 2000],
- [8, 1024],
- ].each { |model_id, dimensions| connection.execute <<-SQL }
- CREATE INDEX IF NOT EXISTS ai_#{type}_embeddings_#{model_id}_1_search_bit ON ai_#{type}_embeddings
- USING hnsw ((binary_quantize(embeddings)::bit(#{dimensions})) bit_hamming_ops)
- WHERE model_id = #{model_id} AND strategy_id = 1;
- SQL
- end
- end
-
- let(:all_idx_names) do
- %w[topics posts document_fragments].reduce([]) do |memo, type|
- (1..8).each { |model_id| memo << "ai_#{type}_embeddings_#{model_id}_1_search_bit" }
-
- memo
- end
- end
-
- context "when there are no embedding definitions" do
- it "removes all indexes" do
- migration.up
-
- remaining_idxs =
- DB.query_single(
- "SELECT indexname FROM pg_indexes WHERE indexname IN (:names)",
- names: all_idx_names,
- )
-
- expect(remaining_idxs).to be_empty
- end
- end
-
- context "when there is an embedding definition with the same dimensions" do
- fab!(:embedding_def) { Fabricate(:embedding_definition, id: 2, dimensions: 1536) }
-
- it "keeps the matching index and removes the rest" do
- expected_model_idxs =
- %w[topics posts document_fragments].reduce([]) do |memo, type|
- memo << "ai_#{type}_embeddings_2_1_search_bit"
- end
-
- migration.up
-
- remaining_idxs =
- DB.query_single(
- "SELECT indexname FROM pg_indexes WHERE indexname IN (:names)",
- names: all_idx_names,
- )
-
- expect(remaining_idxs).to contain_exactly(*expected_model_idxs)
- # This method checks dimensions are correct.
- expect(DiscourseAi::Embeddings::Schema.correctly_indexed?(embedding_def)).to eq(true)
- end
- end
-
- context "when there is an embedding definition with different dimensions" do
- fab!(:embedding_def) { Fabricate(:embedding_definition, id: 2, dimensions: 1536) }
- fab!(:embedding_def_2) { Fabricate(:embedding_definition, id: 3, dimensions: 768) }
-
- it "updates the index to use the right dimensions" do
- expected_model_idxs =
- %w[topics posts document_fragments].reduce([]) do |memo, type|
- memo << "ai_#{type}_embeddings_2_1_search_bit"
- memo << "ai_#{type}_embeddings_3_1_search_bit"
- end
-
- migration.up
-
- remaining_idxs =
- DB.query_single(
- "SELECT indexname FROM pg_indexes WHERE indexname IN (:names)",
- names: all_idx_names,
- )
-
- expect(remaining_idxs).to contain_exactly(*expected_model_idxs)
- # This method checks dimensions are correct.
- expect(DiscourseAi::Embeddings::Schema.correctly_indexed?(embedding_def_2)).to eq(true)
- end
- end
-
- context "when there are indexes outside the pre-seeded range" do
- before { %w[topics posts document_fragments].each { |type| connection.execute <<-SQL } }
- CREATE INDEX IF NOT EXISTS ai_#{type}_embeddings_9_1_search_bit ON ai_#{type}_embeddings
- USING hnsw ((binary_quantize(embeddings)::bit(556)) bit_hamming_ops)
- WHERE model_id = 9 AND strategy_id = 1;
- SQL
-
- let(:all_idx_names) do
- %w[topics posts document_fragments].reduce([]) do |memo, type|
- (1..8).each { |model_id| memo << "ai_#{type}_embeddings_#{model_id}_1_search_bit" }
-
- memo
- end
- end
-
- it "leaves them untouched" do
- expected_model_idxs =
- %w[topics posts document_fragments].reduce([]) do |memo, type|
- memo << "ai_#{type}_embeddings_9_1_search_bit"
- end
-
- migration.up
-
- other_idxs =
- DB.query_single(
- "SELECT indexname FROM pg_indexes WHERE indexname IN (:names)",
- names: expected_model_idxs,
- )
-
- expect(other_idxs).to contain_exactly(*expected_model_idxs)
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20260331024139_split_translation_public_content_setting_spec.rb b/plugins/discourse-ai/spec/db/migrate/20260331024139_split_translation_public_content_setting_spec.rb
deleted file mode 100644
index 0bedfb289b7..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20260331024139_split_translation_public_content_setting_spec.rb
+++ /dev/null
@@ -1,105 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20260331024139_split_translation_public_content_setting",
- )
-
-RSpec.describe SplitTranslationPublicContentSetting do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- def store_setting(name, val, data_type: 3)
- connection.execute <<~SQL
- INSERT INTO site_settings(name, data_type, value, created_at, updated_at)
- VALUES ('#{name}', #{data_type}, '#{val}', NOW(), NOW())
- SQL
- end
-
- def setting_value(name)
- DB.query_single("SELECT value FROM site_settings WHERE name = '#{name}'").first
- end
-
- def setting_exists?(name)
- DB.query_single("SELECT COUNT(*) FROM site_settings WHERE name = '#{name}'").first > 0
- end
-
- fab!(:public_category) { Fabricate(:category, read_restricted: false) }
- fab!(:private_category) { Fabricate(:category, read_restricted: true) }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before { enable_current_plugin }
-
- after do
- connection.execute(
- "DELETE FROM site_settings WHERE name IN ('ai_translation_target_categories', 'ai_translation_personal_messages', 'ai_translation_backfill_limit_to_public_content', 'ai_translation_enabled')",
- )
- end
-
- describe "#up" do
- context "when old setting was false and translation is enabled" do
- before do
- store_setting("ai_translation_enabled", "t")
- store_setting("ai_translation_backfill_limit_to_public_content", "f")
- end
-
- it "sets target_categories to all categories and private_messages to all" do
- migration.up
-
- category_ids = setting_value("ai_translation_target_categories").split("|").map(&:to_i)
- expect(category_ids).to include(public_category.id, private_category.id)
- expect(setting_value("ai_translation_personal_messages")).to eq("all")
- expect(setting_exists?("ai_translation_backfill_limit_to_public_content")).to eq(false)
- end
- end
-
- context "when old setting was false and translation is disabled" do
- before { store_setting("ai_translation_backfill_limit_to_public_content", "f") }
-
- it "still migrates settings and deletes the old setting" do
- migration.up
-
- category_ids = setting_value("ai_translation_target_categories").split("|").map(&:to_i)
- expect(category_ids).to include(public_category.id, private_category.id)
- expect(setting_value("ai_translation_personal_messages")).to eq("all")
- expect(setting_exists?("ai_translation_backfill_limit_to_public_content")).to eq(false)
- end
- end
-
- context "when old setting was default (absent) and translation is enabled" do
- before { store_setting("ai_translation_enabled", "t") }
-
- it "sets target_categories to public categories only" do
- migration.up
-
- category_ids = setting_value("ai_translation_target_categories").split("|").map(&:to_i)
- expect(category_ids).to include(public_category.id)
- expect(category_ids).not_to include(private_category.id)
- expect(setting_value("ai_translation_personal_messages")).to be_nil
- expect(setting_exists?("ai_translation_backfill_limit_to_public_content")).to eq(false)
- end
- end
-
- context "when translation was never used" do
- it "inserts nothing and deletes the old setting if present" do
- store_setting("ai_translation_backfill_limit_to_public_content", "t")
-
- migration.up
-
- expect(setting_value("ai_translation_target_categories")).to be_nil
- expect(setting_value("ai_translation_personal_messages")).to be_nil
- expect(setting_exists?("ai_translation_backfill_limit_to_public_content")).to eq(false)
- end
- end
-
- context "when no settings exist at all" do
- it "does nothing" do
- migration.up
-
- expect(setting_value("ai_translation_target_categories")).to be_nil
- expect(setting_value("ai_translation_personal_messages")).to be_nil
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20260504211108_backfill_reviewable_ai_tool_action_scope_spec.rb b/plugins/discourse-ai/spec/db/migrate/20260504211108_backfill_reviewable_ai_tool_action_scope_spec.rb
deleted file mode 100644
index dfab35af809..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20260504211108_backfill_reviewable_ai_tool_action_scope_spec.rb
+++ /dev/null
@@ -1,75 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20260504211108_backfill_reviewable_ai_tool_action_scope",
- )
-
-RSpec.describe BackfillReviewableAiToolActionScope do
- fab!(:private_group, :group)
- fab!(:private_category) { Fabricate(:private_category, group: private_group) }
- fab!(:private_topic) { Fabricate(:topic, category: private_category) }
- fab!(:private_post) { Fabricate(:post, topic: private_topic) }
- fab!(:ai_agent)
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before { enable_current_plugin }
-
- def create_unscoped_reviewable(post_id:)
- tool_action =
- AiToolAction.create!(
- tool_name: "close_topic",
- tool_parameters: {
- topic_id: private_topic.id,
- },
- ai_agent: ai_agent,
- bot_user_id: Discourse.system_user.id,
- post_id: post_id,
- )
-
- reviewable =
- ReviewableAiToolAction.needs_review!(
- target: tool_action,
- created_by: Discourse.system_user,
- reviewable_by_moderator: true,
- payload: {
- agent_name: "Test Agent",
- },
- )
-
- reviewable.update_columns(topic_id: nil, category_id: nil)
- reviewable
- end
-
- it "backfills topic and category for reviewables whose target action has a post" do
- reviewable = create_unscoped_reviewable(post_id: private_post.id)
-
- described_class.new.up
-
- reviewable.reload
- expect(reviewable.topic_id).to eq(private_topic.id)
- expect(reviewable.category_id).to eq(private_category.id)
- end
-
- it "leaves topic and category nil when the target action has no post" do
- reviewable = create_unscoped_reviewable(post_id: nil)
-
- described_class.new.up
-
- reviewable.reload
- expect(reviewable.topic_id).to be_nil
- expect(reviewable.category_id).to be_nil
- end
-
- it "does not overwrite reviewables that are already scoped" do
- reviewable = create_unscoped_reviewable(post_id: private_post.id)
- other_topic = Fabricate(:topic)
- reviewable.update_columns(topic_id: other_topic.id, category_id: other_topic.category_id)
-
- described_class.new.up
-
- reviewable.reload
- expect(reviewable.topic_id).to eq(other_topic.id)
- expect(reviewable.category_id).to eq(other_topic.category_id)
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20260513162531_convert_ai_translation_target_categories_to_excluded_categories_spec.rb b/plugins/discourse-ai/spec/db/migrate/20260513162531_convert_ai_translation_target_categories_to_excluded_categories_spec.rb
deleted file mode 100644
index 6f9ecc0fede..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20260513162531_convert_ai_translation_target_categories_to_excluded_categories_spec.rb
+++ /dev/null
@@ -1,137 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20260513162531_convert_ai_translation_target_categories_to_excluded_categories",
- )
-
-RSpec.describe ConvertAiTranslationTargetCategoriesToExcludedCategories do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- fab!(:category_1, :category)
- fab!(:category_2, :category)
- fab!(:category_3, :category)
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before do
- enable_current_plugin
- delete_settings
- end
-
- after { delete_settings }
-
- def delete_settings
- connection.execute(
- "DELETE FROM site_settings WHERE name IN ('ai_translation_target_categories', 'ai_translation_excluded_categories', 'ai_translation_enabled')",
- )
- end
-
- def store_setting(name, val, data_type: 20)
- connection.execute <<~SQL
- INSERT INTO site_settings(name, data_type, value, created_at, updated_at)
- VALUES ('#{name}', #{data_type}, '#{val}', NOW(), NOW())
- SQL
- end
-
- def setting_value(name)
- DB.query_single("SELECT value FROM site_settings WHERE name = '#{name}'").first
- end
-
- def setting_exists?(name)
- DB.query_single("SELECT COUNT(*) FROM site_settings WHERE name = '#{name}'").first > 0
- end
-
- def all_category_ids
- DB.query_single("SELECT id FROM categories").map(&:to_i)
- end
-
- describe "#up" do
- before { Migration::Helpers.stubs(:existing_site?).returns(true) }
-
- it "converts target categories to excluded categories for existing sites" do
- store_setting("ai_translation_target_categories", "#{category_1.id}|#{category_3.id}")
-
- migration.up
-
- excluded_category_ids =
- setting_value("ai_translation_excluded_categories").split("|").map(&:to_i)
- expect(excluded_category_ids).to contain_exactly(
- *(all_category_ids - [category_1.id, category_3.id]),
- )
- expect(setting_exists?("ai_translation_target_categories")).to eq(false)
- end
-
- it "converts saved target categories when translation is disabled" do
- store_setting("ai_translation_enabled", "f", data_type: 5)
- store_setting("ai_translation_target_categories", category_1.id.to_s)
-
- migration.up
-
- excluded_category_ids =
- setting_value("ai_translation_excluded_categories").split("|").map(&:to_i)
- expect(excluded_category_ids).to contain_exactly(*(all_category_ids - [category_1.id]))
- expect(setting_exists?("ai_translation_target_categories")).to eq(false)
- end
-
- it "excludes all categories for existing sites with translation enabled and an empty target list" do
- store_setting("ai_translation_enabled", "t", data_type: 5)
- store_setting("ai_translation_target_categories", "")
-
- migration.up
-
- excluded_category_ids =
- setting_value("ai_translation_excluded_categories").split("|").map(&:to_i)
- expect(excluded_category_ids).to contain_exactly(*all_category_ids)
- expect(setting_exists?("ai_translation_target_categories")).to eq(false)
- end
-
- it "does not store an excluded list for disabled sites with an empty target list" do
- store_setting("ai_translation_enabled", "f", data_type: 5)
- store_setting("ai_translation_target_categories", "")
-
- migration.up
-
- expect(setting_value("ai_translation_excluded_categories")).to be_nil
- expect(setting_exists?("ai_translation_target_categories")).to eq(false)
- end
-
- it "excludes all categories for existing sites with translation enabled and without a stored target list" do
- store_setting("ai_translation_enabled", "t", data_type: 5)
-
- migration.up
-
- excluded_category_ids =
- setting_value("ai_translation_excluded_categories").split("|").map(&:to_i)
- expect(excluded_category_ids).to contain_exactly(*all_category_ids)
- end
-
- it "does not store an excluded list for disabled sites without a stored target list" do
- store_setting("ai_translation_enabled", "f", data_type: 5)
-
- migration.up
-
- expect(setting_value("ai_translation_excluded_categories")).to be_nil
- end
-
- it "does not store an excluded list when all existing categories were targets" do
- store_setting("ai_translation_target_categories", all_category_ids.join("|"))
-
- migration.up
-
- expect(setting_value("ai_translation_excluded_categories")).to be_nil
- expect(setting_exists?("ai_translation_target_categories")).to eq(false)
- end
-
- it "does not migrate target categories on new sites" do
- Migration::Helpers.stubs(:existing_site?).returns(false)
- store_setting("ai_translation_target_categories", category_1.id.to_s)
-
- migration.up
-
- expect(setting_value("ai_translation_excluded_categories")).to be_nil
- expect(setting_exists?("ai_translation_target_categories")).to eq(false)
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20260708051450_remove_image_caption_from_ai_helper_enabled_features_spec.rb b/plugins/discourse-ai/spec/db/migrate/20260708051450_remove_image_caption_from_ai_helper_enabled_features_spec.rb
deleted file mode 100644
index d0c991f9acd..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20260708051450_remove_image_caption_from_ai_helper_enabled_features_spec.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20260708051450_remove_image_caption_from_ai_helper_enabled_features",
- )
-
-describe RemoveImageCaptionFromAiHelperEnabledFeatures do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before { delete_setting }
-
- after { delete_setting }
-
- def delete_setting
- connection.execute("DELETE FROM site_settings WHERE name = 'ai_helper_enabled_features'")
- end
-
- def store_enabled_features(value)
- connection.execute <<~SQL
- INSERT INTO site_settings(name, data_type, value, created_at, updated_at)
- VALUES ('ai_helper_enabled_features', 20, '#{value}', NOW(), NOW())
- SQL
- end
-
- def enabled_features
- DB.query_single(
- "SELECT value FROM site_settings WHERE name = 'ai_helper_enabled_features'",
- ).first
- end
-
- it "removes the image caption feature from stored helper features", :aggregate_failures do
- store_enabled_features("suggestions|image_caption|context_menu")
-
- migration.up
-
- expect(enabled_features).to eq("suggestions|context_menu")
-
- delete_setting
- store_enabled_features("image_caption")
-
- migration.up
-
- expect(enabled_features).to eq("")
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20260708080308_convert_ai_translation_excluded_categories_to_category_scope_spec.rb b/plugins/discourse-ai/spec/db/migrate/20260708080308_convert_ai_translation_excluded_categories_to_category_scope_spec.rb
deleted file mode 100644
index 8aae75f7abc..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20260708080308_convert_ai_translation_excluded_categories_to_category_scope_spec.rb
+++ /dev/null
@@ -1,91 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20260708080308_convert_ai_translation_excluded_categories_to_category_scope",
- )
-
-describe ConvertAiTranslationExcludedCategoriesToCategoryScope do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- fab!(:category_1, :category)
- fab!(:category_2, :category)
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before do
- enable_current_plugin
- delete_settings
- end
-
- after { delete_settings }
-
- def delete_settings
- connection.execute(
- "DELETE FROM site_settings WHERE name IN ('ai_translation_excluded_categories', 'ai_translation_enabled', 'ai_translation_category_scope', 'ai_translation_categories')",
- )
- end
-
- def store_setting(name, val, data_type:)
- connection.execute <<~SQL
- INSERT INTO site_settings(name, data_type, value, created_at, updated_at)
- VALUES ('#{name}', #{data_type}, '#{val}', NOW(), NOW())
- SQL
- end
-
- def setting_value(name)
- DB.query_single("SELECT value FROM site_settings WHERE name = '#{name}'").first
- end
-
- def setting_exists?(name)
- DB.query_single("SELECT COUNT(*) FROM site_settings WHERE name = '#{name}'").first > 0
- end
-
- describe "#up" do
- it "converts excluded categories to an exact exclude category scope" do
- store_setting(
- "ai_translation_excluded_categories",
- "#{category_1.id}|#{category_2.id}",
- data_type: 11,
- )
-
- migration.up
-
- expect(setting_value("ai_translation_category_scope")).to eq("exclude_strict")
- expect(setting_value("ai_translation_categories")).to eq("#{category_1.id}|#{category_2.id}")
- expect(setting_exists?("ai_translation_excluded_categories")).to eq(false)
- end
-
- it "preserves all categories for enabled sites with empty excluded categories" do
- store_setting("ai_translation_enabled", "t", data_type: 5)
- store_setting("ai_translation_excluded_categories", "", data_type: 11)
-
- migration.up
-
- expect(setting_value("ai_translation_category_scope")).to eq("all")
- expect(setting_value("ai_translation_categories")).to be_nil
- expect(setting_exists?("ai_translation_excluded_categories")).to eq(false)
- end
-
- it "preserves all categories for enabled sites without stored excluded categories" do
- store_setting("ai_translation_enabled", "t", data_type: 5)
-
- migration.up
-
- expect(setting_value("ai_translation_category_scope")).to eq("all")
- expect(setting_value("ai_translation_categories")).to be_nil
- end
-
- it "uses the public categories default for disabled sites with empty excluded categories" do
- store_setting("ai_translation_enabled", "f", data_type: 5)
- store_setting("ai_translation_excluded_categories", "", data_type: 11)
-
- migration.up
-
- expect(setting_value("ai_translation_category_scope")).to be_nil
- expect(setting_value("ai_translation_categories")).to be_nil
- expect(setting_exists?("ai_translation_excluded_categories")).to eq(false)
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/migrate/20260727085824_convert_ai_translation_backfill_max_age_to_start_date_spec.rb b/plugins/discourse-ai/spec/db/migrate/20260727085824_convert_ai_translation_backfill_max_age_to_start_date_spec.rb
deleted file mode 100644
index 383a28cb41f..00000000000
--- a/plugins/discourse-ai/spec/db/migrate/20260727085824_convert_ai_translation_backfill_max_age_to_start_date_spec.rb
+++ /dev/null
@@ -1,139 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/migrate/20260727085824_convert_ai_translation_backfill_max_age_to_start_date",
- )
-
-describe ConvertAiTranslationBackfillMaxAgeToStartDate do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before do
- enable_current_plugin
- delete_settings
- end
-
- after { delete_settings }
-
- def delete_settings
- connection.execute(<<~SQL)
- DELETE FROM site_settings
- WHERE name IN (
- 'discourse_ai_enabled',
- 'ai_translation_enabled',
- 'ai_translation_backfill_hourly_rate',
- 'ai_translation_backfill_max_age_days',
- 'ai_translation_backfill_start_date'
- )
- SQL
- end
-
- def store_setting(name, value, data_type)
- DB.exec(<<~SQL, name:, value:, data_type:)
- INSERT INTO site_settings(name, data_type, value, created_at, updated_at)
- VALUES (:name, :data_type, :value, NOW(), NOW())
- SQL
- end
-
- def configure_backfill(
- discourse_ai_enabled: true,
- ai_translation_enabled: true,
- hourly_rate: 50,
- max_age_days: 30
- )
- unless discourse_ai_enabled.nil?
- store_setting("discourse_ai_enabled", discourse_ai_enabled ? "t" : "f", 5)
- end
- unless ai_translation_enabled.nil?
- store_setting("ai_translation_enabled", ai_translation_enabled ? "t" : "f", 5)
- end
- store_setting("ai_translation_backfill_hourly_rate", hourly_rate, 3) if hourly_rate
- store_setting("ai_translation_backfill_max_age_days", max_age_days, 3) if max_age_days
- end
-
- def setting(name)
- DB.query("SELECT data_type, value FROM site_settings WHERE name = :name", name:).first
- end
-
- def utc_date
- DB.query_single("SELECT (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')::date").first
- end
-
- describe "#up" do
- it "converts a positive max age override to a fixed UTC date" do
- configure_backfill
-
- expected_start_date = (utc_date - 30).iso8601
-
- migration.up
-
- migrated_setting = setting("ai_translation_backfill_start_date")
- expect(migrated_setting.data_type).to eq(33)
- expect(migrated_setting.value).to eq(expected_start_date)
- expect(setting("ai_translation_backfill_max_age_days").value).to eq("30")
- end
-
- it "uses blank when the max age disables backfilling" do
- configure_backfill(max_age_days: 0)
-
- migration.up
-
- expect(setting("ai_translation_backfill_start_date")).to be_nil
- expect(setting("ai_translation_backfill_max_age_days").value).to eq("0")
- end
-
- it "uses blank when the hourly rate disables backfilling" do
- configure_backfill(hourly_rate: 0)
-
- migration.up
-
- expect(setting("ai_translation_backfill_start_date")).to be_nil
- end
-
- it "uses blank when Discourse AI is disabled" do
- configure_backfill(discourse_ai_enabled: nil)
-
- migration.up
-
- expect(setting("ai_translation_backfill_start_date")).to be_nil
- end
-
- it "uses blank when AI translation is disabled" do
- configure_backfill(ai_translation_enabled: nil)
-
- migration.up
-
- expect(setting("ai_translation_backfill_start_date")).to be_nil
- end
-
- it "converts the previous five-day default when backfilling is enabled" do
- configure_backfill(hourly_rate: nil, max_age_days: nil)
-
- expected_start_date = (utc_date - 5).iso8601
-
- migration.up
-
- migrated_setting = setting("ai_translation_backfill_start_date")
- expect(migrated_setting.data_type).to eq(33)
- expect(migrated_setting.value).to eq(expected_start_date)
- end
-
- it "keeps an existing start date" do
- configure_backfill
- store_setting("ai_translation_backfill_start_date", "2026-07-01", 33)
-
- migration.up
-
- expect(setting("ai_translation_backfill_start_date").value).to eq("2026-07-01")
- end
-
- it "does not create a start date when no previous settings exist" do
- migration.up
-
- expect(setting("ai_translation_backfill_start_date")).to be_nil
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/db/post_migrate/backfill_ai_summary_locales_spec.rb b/plugins/discourse-ai/spec/db/post_migrate/backfill_ai_summary_locales_spec.rb
deleted file mode 100644
index 06985b9ce4d..00000000000
--- a/plugins/discourse-ai/spec/db/post_migrate/backfill_ai_summary_locales_spec.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-ai/db/post_migrate/20260721080420_backfill_ai_summary_locales.rb",
- )
-
-RSpec.describe BackfillAiSummaryLocales do
- fab!(:localized_topic) { Fabricate(:topic, locale: "fr") }
- fab!(:locale_less_topic) { Fabricate(:topic, locale: nil) }
-
- before do
- @migration_verbose = ActiveRecord::Migration.verbose
- ActiveRecord::Migration.verbose = false
- end
-
- after { ActiveRecord::Migration.verbose = @migration_verbose }
-
- it "backfills locale-less topic summaries from the topic or default locale" do
- source_summary = Fabricate(:ai_summary, target: localized_topic, locale: nil)
- default_summary = Fabricate(:ai_summary, target: locale_less_topic, locale: nil)
- existing_localized_summary =
- Fabricate(
- :ai_summary,
- target: locale_less_topic,
- summary_type: AiSummary.summary_types[:gist],
- locale: "he",
- )
-
- described_class.new.up
-
- expect(source_summary.reload.locale).to eq("fr")
- expect(default_summary.reload.locale).to eq("en")
- expect(existing_localized_summary.reload.locale).to eq("he")
- end
-end
diff --git a/plugins/discourse-ai/spec/jobs/scheduled/sentiment_backfill_spec.rb b/plugins/discourse-ai/spec/jobs/scheduled/sentiment_backfill_spec.rb
index 8069a25a0c8..db56f30d1b2 100644
--- a/plugins/discourse-ai/spec/jobs/scheduled/sentiment_backfill_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/scheduled/sentiment_backfill_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../../support/sentiment_inference_stubs"
-
RSpec.describe Jobs::SentimentBackfill do
subject(:job) { described_class.new }
diff --git a/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb b/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb
index 6667bccb644..a8a63422c9d 100644
--- a/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb
+++ b/plugins/discourse-ai/spec/jobs/shared_conversation_adjust_upload_security_spec.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
RSpec.describe Jobs::SharedConversationAdjustUploadSecurity do
+ subject(:run_job) { described_class.new.execute(params) }
+
let(:params) { {} }
fab!(:claude_2) { Fabricate(:llm_model, name: "claude-2") }
@@ -20,10 +22,6 @@ RSpec.describe Jobs::SharedConversationAdjustUploadSecurity do
fab!(:post_2) { Fabricate(:post, topic: topic, user: user) }
fab!(:conversation) { SharedAiConversation.share_conversation(user, topic) }
- def run_job
- described_class.new.execute(params)
- end
-
before { enable_current_plugin }
context "when conversation is created" do
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb
index 2bbaa4a66e3..4c876c5c10f 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/setting_context_spec.rb
@@ -1,14 +1,7 @@
# frozen_string_literal: true
-def has_rg?
- if defined?(@has_rg)
- @has_rg
- else
- @has_rg |= system("which rg", out: File::NULL)
- end
-end
-
-RSpec.describe DiscourseAi::Agents::Tools::SettingContext, if: has_rg? do
+RSpec.describe DiscourseAi::Agents::Tools::SettingContext,
+ if: system("which rg", out: File::NULL) do
fab!(:llm_model)
let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }
@@ -19,13 +12,14 @@ RSpec.describe DiscourseAi::Agents::Tools::SettingContext, if: has_rg? do
SiteSetting.ai_bot_enabled = true
end
- def setting_context(setting_name)
- described_class.new({ setting_name: setting_name }, bot_user: bot_user, llm: llm)
- end
-
describe "#execute" do
it "returns the context for core setting" do
- result = setting_context("moderators_view_emails").invoke
+ result =
+ described_class.new(
+ { setting_name: "moderators_view_emails" },
+ bot_user: bot_user,
+ llm: llm,
+ ).invoke
expect(result[:setting_name]).to eq("moderators_view_emails")
@@ -34,7 +28,12 @@ RSpec.describe DiscourseAi::Agents::Tools::SettingContext, if: has_rg? do
end
it "supports spaces and case insensitive setting name" do
- result = setting_context("moderaTors View Emails").invoke
+ result =
+ described_class.new(
+ { setting_name: "moderaTors View Emails" },
+ bot_user: bot_user,
+ llm: llm,
+ ).invoke
expect(result[:setting_name]).to eq("moderators_view_emails")
@@ -43,7 +42,8 @@ RSpec.describe DiscourseAi::Agents::Tools::SettingContext, if: has_rg? do
end
it "returns the context for plugin setting" do
- result = setting_context("ai_bot_enabled").invoke
+ result =
+ described_class.new({ setting_name: "ai_bot_enabled" }, bot_user: bot_user, llm: llm).invoke
expect(result[:setting_name]).to eq("ai_bot_enabled")
expect(result[:context]).to include("ai_bot_enabled:")
@@ -51,7 +51,12 @@ RSpec.describe DiscourseAi::Agents::Tools::SettingContext, if: has_rg? do
context "when the setting does not exist" do
it "returns an error message" do
- result = setting_context("this_setting_does_not_exist").invoke
+ result =
+ described_class.new(
+ { setting_name: "this_setting_does_not_exist" },
+ bot_user: bot_user,
+ llm: llm,
+ ).invoke
expect(result[:context]).to eq("This setting does not exist")
end
diff --git a/plugins/discourse-ai/spec/lib/modules/sentiment/entry_point_spec.rb b/plugins/discourse-ai/spec/lib/modules/sentiment/entry_point_spec.rb
index f7204b84c41..82fd738c4ac 100644
--- a/plugins/discourse-ai/spec/lib/modules/sentiment/entry_point_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/sentiment/entry_point_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../../../support/sentiment_inference_stubs"
-
RSpec.describe DiscourseAi::Sentiment::EntryPoint do
fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
@@ -57,28 +55,43 @@ RSpec.describe DiscourseAi::Sentiment::EntryPoint do
fab!(:post_2, :post)
describe "overall_sentiment report" do
- let(:positive_classification) { { negative: 0.2, neutral: 0.3, positive: 0.7 } }
- let(:negative_classification) { { negative: 0.65, neutral: 0.2, positive: 0.1 } }
-
- def sentiment_classification(post, classification)
- Fabricate(:sentiment_classification, target: post, classification: classification)
+ fab!(:post_1_classification) do
+ Fabricate(
+ :sentiment_classification,
+ target: post_1,
+ classification: {
+ negative: 0.2,
+ neutral: 0.3,
+ positive: 0.7,
+ },
+ )
+ end
+ fab!(:post_2_classification) do
+ Fabricate(
+ :sentiment_classification,
+ target: post_2,
+ classification: {
+ negative: 0.65,
+ neutral: 0.2,
+ positive: 0.1,
+ },
+ )
+ end
+ fab!(:private_message_classification) do
+ Fabricate(
+ :sentiment_classification,
+ target: pm,
+ classification: post_1_classification.classification,
+ )
end
it "calculate averages using only public posts" do
- sentiment_classification(post_1, positive_classification)
- sentiment_classification(post_2, negative_classification)
- sentiment_classification(pm, positive_classification)
-
report = Report.find("overall_sentiment")
overall_sentiment = report.data[0][:data][0][:y].to_i
expect(overall_sentiment).to eq(0)
end
it "exports the report without any errors" do
- sentiment_classification(post_1, positive_classification)
- sentiment_classification(post_2, negative_classification)
- sentiment_classification(pm, positive_classification)
-
exporter = Jobs::ExportCsvFile.new
exporter.entity = "report"
exporter.extra = ActiveSupport::HashWithIndifferentAccess.new(name: "overall_sentiment")
@@ -90,99 +103,99 @@ RSpec.describe DiscourseAi::Sentiment::EntryPoint do
end
describe "post_emotion report" do
- let(:emotion_1) do
- {
- love: 0.9444406,
- admiration: 0.013724019,
- surprise: 0.010188869,
- excitement: 0.007888741,
- curiosity: 0.006301749,
- joy: 0.004060776,
- confusion: 0.0028238264,
- approval: 0.0018160914,
- realization: 0.001174849,
- neutral: 0.0008561869,
- amusement: 0.00075853954,
- disapproval: 0.0006987994,
- disappointment: 0.0006166883,
- anger: 0.0006000542,
- annoyance: 0.0005615011,
- desire: 0.00046368592,
- fear: 0.00045117878,
- sadness: 0.00041727215,
- gratitude: 0.00041727215,
- optimism: 0.00037112957,
- disgust: 0.00035552034,
- nervousness: 0.00022954118,
- embarrassment: 0.0002049572,
- caring: 0.00017737568,
- remorse: 0.00011407586,
- grief: 0.0001006716,
- pride: 0.00009681493,
- relief: 0.00008919009,
- }
- end
- let(:emotion_2) do
- {
- love: 0.8444406,
- admiration: 0.113724019,
- surprise: 0.010188869,
- excitement: 0.007888741,
- curiosity: 0.006301749,
- joy: 0.004060776,
- confusion: 0.0028238264,
- approval: 0.0018160914,
- realization: 0.001174849,
- neutral: 0.0008561869,
- amusement: 0.00075853954,
- disapproval: 0.0006987994,
- disappointment: 0.0006166883,
- anger: 0.0006000542,
- annoyance: 0.0005615011,
- desire: 0.00046368592,
- fear: 0.00045117878,
- sadness: 0.00041727215,
- gratitude: 0.00041727215,
- optimism: 0.00037112957,
- disgust: 0.00035552034,
- nervousness: 0.00022954118,
- embarrassment: 0.0002049572,
- caring: 0.00017737568,
- remorse: 0.00011407586,
- grief: 0.0001006716,
- pride: 0.00009681493,
- relief: 0.00008919009,
- }
+ fab!(:post_1_classification) do
+ Fabricate(
+ :sentiment_classification,
+ target: post_1,
+ model_used: "SamLowe/roberta-base-go_emotions",
+ classification: {
+ love: 0.9444406,
+ admiration: 0.013724019,
+ surprise: 0.010188869,
+ excitement: 0.007888741,
+ curiosity: 0.006301749,
+ joy: 0.004060776,
+ confusion: 0.0028238264,
+ approval: 0.0018160914,
+ realization: 0.001174849,
+ neutral: 0.0008561869,
+ amusement: 0.00075853954,
+ disapproval: 0.0006987994,
+ disappointment: 0.0006166883,
+ anger: 0.0006000542,
+ annoyance: 0.0005615011,
+ desire: 0.00046368592,
+ fear: 0.00045117878,
+ sadness: 0.00041727215,
+ gratitude: 0.00041727215,
+ optimism: 0.00037112957,
+ disgust: 0.00035552034,
+ nervousness: 0.00022954118,
+ embarrassment: 0.0002049572,
+ caring: 0.00017737568,
+ remorse: 0.00011407586,
+ grief: 0.0001006716,
+ pride: 0.00009681493,
+ relief: 0.00008919009,
+ },
+ )
end
- let(:model_used) { "SamLowe/roberta-base-go_emotions" }
-
- def emotion_classification(post, classification)
+ fab!(:post_2_classification) do
Fabricate(
:sentiment_classification,
- target: post,
- model_used: model_used,
- classification: classification,
+ target: post_2,
+ model_used: "SamLowe/roberta-base-go_emotions",
+ classification: {
+ love: 0.8444406,
+ admiration: 0.113724019,
+ surprise: 0.010188869,
+ excitement: 0.007888741,
+ curiosity: 0.006301749,
+ joy: 0.004060776,
+ confusion: 0.0028238264,
+ approval: 0.0018160914,
+ realization: 0.001174849,
+ neutral: 0.0008561869,
+ amusement: 0.00075853954,
+ disapproval: 0.0006987994,
+ disappointment: 0.0006166883,
+ anger: 0.0006000542,
+ annoyance: 0.0005615011,
+ desire: 0.00046368592,
+ fear: 0.00045117878,
+ sadness: 0.00041727215,
+ gratitude: 0.00041727215,
+ optimism: 0.00037112957,
+ disgust: 0.00035552034,
+ nervousness: 0.00022954118,
+ embarrassment: 0.0002049572,
+ caring: 0.00017737568,
+ remorse: 0.00011407586,
+ grief: 0.0001006716,
+ pride: 0.00009681493,
+ relief: 0.00008919009,
+ },
)
end
-
- def strip_emoji_and_downcase(str)
- stripped_str = str.gsub(/[^\p{L}\p{N}]+/, "") # remove any non-alphanumeric characters
- stripped_str.downcase
+ fab!(:private_message_classification) do
+ Fabricate(
+ :sentiment_classification,
+ target: pm,
+ model_used: "SamLowe/roberta-base-go_emotions",
+ classification: post_2_classification.classification,
+ )
end
it "calculate averages using only public posts" do
threshold = 0.10
-
- emotion_classification(post_1, emotion_1)
- emotion_classification(post_2, emotion_2)
- emotion_classification(pm, emotion_2)
-
report = Report.find("emotion_love")
data_point = report.data
data_point.each do |point|
- expected = (emotion_1[:love] > threshold ? 1 : 0) + (emotion_2[:love] > threshold ? 1 : 0)
+ expected =
+ (post_1_classification.classification["love"] > threshold ? 1 : 0) +
+ (post_2_classification.classification["love"] > threshold ? 1 : 0)
expect(point[:y]).to eq(expected)
end
end
diff --git a/plugins/discourse-ai/spec/lib/modules/sentiment/jobs/regular/post_sentiment_analysis_spec.rb b/plugins/discourse-ai/spec/lib/modules/sentiment/jobs/regular/post_sentiment_analysis_spec.rb
index 19c6bb5203c..cce1452b2ec 100644
--- a/plugins/discourse-ai/spec/lib/modules/sentiment/jobs/regular/post_sentiment_analysis_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/sentiment/jobs/regular/post_sentiment_analysis_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../../../../../support/sentiment_inference_stubs"
-
describe Jobs::PostSentimentAnalysis do
subject(:job) { described_class.new }
diff --git a/plugins/discourse-ai/spec/lib/modules/sentiment/post_classification_spec.rb b/plugins/discourse-ai/spec/lib/modules/sentiment/post_classification_spec.rb
index 10e0a04bcfd..980463cac11 100644
--- a/plugins/discourse-ai/spec/lib/modules/sentiment/post_classification_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/sentiment/post_classification_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../../../support/sentiment_inference_stubs"
-
RSpec.describe DiscourseAi::Sentiment::PostClassification do
subject(:post_classification) { described_class.new }
@@ -12,25 +10,6 @@ RSpec.describe DiscourseAi::Sentiment::PostClassification do
"[{\"model_name\":\"SamLowe/roberta-base-go_emotions\",\"endpoint\":\"http://samlowe-emotion.com\",\"api_key\":\"123\"},{\"model_name\":\"j-hartmann/emotion-english-distilroberta-base\",\"endpoint\":\"http://jhartmann-emotion.com\",\"api_key\":\"123\"},{\"model_name\":\"cardiffnlp/twitter-roberta-base-sentiment-latest\",\"endpoint\":\"http://cardiffnlp-sentiment.com\",\"api_key\":\"123\"}]"
end
- def check_classification_for(post)
- result =
- ClassificationResult.find_by(
- model_used: "cardiffnlp/twitter-roberta-base-sentiment-latest",
- target: post,
- )
-
- expect(result.classification.keys).to contain_exactly("negative", "neutral", "positive")
- end
-
- def agent_for(response_format, llm_model)
- Fabricate(
- :ai_agent,
- default_llm: llm_model,
- response_format: response_format,
- system_prompt: "Classify this post",
- )
- end
-
describe ".active_model_name_for" do
it "uses an explicitly typed custom sentiment classifier for read paths" do
SiteSetting.ai_sentiment_model_configs = [
@@ -88,7 +67,13 @@ RSpec.describe DiscourseAi::Sentiment::PostClassification do
SentimentInferenceStubs.stub_classification(post_1)
post_classification.classify!(post_1)
- check_classification_for(post_1)
+
+ result =
+ ClassificationResult.find_by(
+ model_used: "cardiffnlp/twitter-roberta-base-sentiment-latest",
+ target: post_1,
+ )
+ expect(result.classification.keys).to contain_exactly("negative", "neutral", "positive")
end
it "does nothing if there are no classification model" do
@@ -117,106 +102,101 @@ RSpec.describe DiscourseAi::Sentiment::PostClassification do
expect(new_classifications).to eq(1)
end
- it "classifies sentiment through a configured agent" do
- llm_model = Fabricate(:fake_model)
- ai_agent =
- agent_for(
- %w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
- llm_model,
+ context "with an agent" do
+ fab!(:llm_model, :fake_model)
+ fab!(:ai_agent) do
+ Fabricate(
+ :ai_agent,
+ default_llm: llm_model,
+ response_format:
+ %w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
+ system_prompt: "Classify this post",
)
- SiteSetting.ai_sentiment_model_configs = ""
- SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
- SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
-
- DiscourseAi::Completions::Llm.with_prepared_responses(
- [{ negative: 0.1, neutral: 0.2, positive: 0.7 }],
- ) { post_classification.classify!(post_1) }
+ end
- result =
- ClassificationResult.find_by!(
- model_used: DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
- target: post_1,
- )
+ it "classifies sentiment through a configured agent" do
+ SiteSetting.ai_sentiment_model_configs = ""
+ SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
- expect(result.classification).to eq("negative" => 0.1, "neutral" => 0.2, "positive" => 0.7)
- end
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ [{ negative: 0.1, neutral: 0.2, positive: 0.7 }],
+ ) { post_classification.classify!(post_1) }
- it "classifies emotion through a configured agent" do
- llm_model = Fabricate(:fake_model)
- ai_agent =
- agent_for(
- DiscourseAi::Sentiment::Emotions::LIST.map do |label|
- { "key" => label, "type" => "number" }
- end,
- llm_model,
- )
- SiteSetting.ai_sentiment_model_configs = ""
- SiteSetting.ai_sentiment_emotion_classification_strategy = "agent"
- SiteSetting.ai_sentiment_emotion_agent = ai_agent.id
+ result =
+ ClassificationResult.find_by!(
+ model_used: DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
+ target: post_1,
+ )
- DiscourseAi::Completions::Llm.with_prepared_responses(
- [{ anger: 0.7, joy: 0.2, neutral: 0.1 }],
- ) { post_classification.classify!(post_1) }
+ expect(result.classification).to eq("negative" => 0.1, "neutral" => 0.2, "positive" => 0.7)
+ end
- result =
- ClassificationResult.find_by!(
- model_used: DiscourseAi::Sentiment::Constants::EMOTION_AGENT_MODEL,
- target: post_1,
+ it "classifies emotion through a configured agent" do
+ ai_agent.update!(
+ response_format:
+ DiscourseAi::Sentiment::Emotions::LIST.map do |label|
+ { "key" => label, "type" => "number" }
+ end,
)
-
- expect(result.classification.keys).to contain_exactly(*DiscourseAi::Sentiment::Emotions::LIST)
- expect(result.classification.slice("anger", "joy", "neutral")).to eq(
- "anger" => 0.7,
- "joy" => 0.2,
- "neutral" => 0.1,
- )
- end
-
- it "skips a lone legacy untyped sentiment config when sentiment strategy is agent" do
- llm_model = Fabricate(:fake_model)
- ai_agent =
- agent_for(
- %w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
- llm_model,
+ SiteSetting.ai_sentiment_model_configs = ""
+ SiteSetting.ai_sentiment_emotion_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_emotion_agent = ai_agent.id
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ [{ anger: 0.7, joy: 0.2, neutral: 0.1 }],
+ ) { post_classification.classify!(post_1) }
+
+ result =
+ ClassificationResult.find_by!(
+ model_used: DiscourseAi::Sentiment::Constants::EMOTION_AGENT_MODEL,
+ target: post_1,
+ )
+
+ expect(result.classification.keys).to contain_exactly(
+ *DiscourseAi::Sentiment::Emotions::LIST,
)
- SiteSetting.ai_sentiment_model_configs = [
- { model_name: "custom/legacy", endpoint: "https://legacy.example.com", api_key: "123" },
- ].to_json
- SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
- SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
-
- model_names = post_classification.classifiers.map { |c| c[:model_name] }
- expect(model_names).to include(DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL)
- expect(model_names).not_to include("custom/legacy")
- end
-
- it "skips storing when the agent returns no usable classification" do
- llm_model = Fabricate(:fake_model)
- ai_agent =
- agent_for(
- %w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
- llm_model,
+ expect(result.classification.slice("anger", "joy", "neutral")).to eq(
+ "anger" => 0.7,
+ "joy" => 0.2,
+ "neutral" => 0.1,
)
- SiteSetting.ai_sentiment_model_configs = ""
- SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
- SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
+ end
+
+ it "skips a lone legacy untyped sentiment config when sentiment strategy is agent" do
+ SiteSetting.ai_sentiment_model_configs = [
+ { model_name: "custom/legacy", endpoint: "https://legacy.example.com", api_key: "123" },
+ ].to_json
+ SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
- DiscourseAi::Completions::Llm.with_prepared_responses(["not json"]) do
- post_classification.classify!(post_1)
+ model_names = post_classification.classifiers.map { |c| c[:model_name] }
+ expect(model_names).to include(DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL)
+ expect(model_names).not_to include("custom/legacy")
end
- expect(
- ClassificationResult.where(
- model_used: DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
- target: post_1,
- ),
- ).to be_empty
+ it "skips storing when the agent returns no usable classification" do
+ SiteSetting.ai_sentiment_model_configs = ""
+ SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(["not json"]) do
+ post_classification.classify!(post_1)
+ end
+
+ expect(
+ ClassificationResult.where(
+ model_used: DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
+ target: post_1,
+ ),
+ ).to be_empty
+ end
end
- it "falls back to the newest LLM model when the configured agent does not set a default LLM" do
- Fabricate(:fake_model, name: "older-model", created_at: 1.day.ago)
- llm_model = Fabricate(:fake_model, name: "newer-model")
- ai_agent =
+ context "when the configured agent does not set a default LLM" do
+ fab!(:older_llm_model) { Fabricate(:fake_model, name: "older-model", created_at: 1.day.ago) }
+ fab!(:newest_llm_model) { Fabricate(:fake_model, name: "newer-model") }
+ fab!(:agent_without_default_llm) do
Fabricate(
:ai_agent,
default_llm: nil,
@@ -224,20 +204,24 @@ RSpec.describe DiscourseAi::Sentiment::PostClassification do
%w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
system_prompt: "Classify this post",
)
- SiteSetting.ai_default_llm_model = ""
- SiteSetting.ai_sentiment_model_configs = ""
- SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
- SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
-
- classifier =
- post_classification.send(
- :agent_classifier,
- :sentiment,
- ai_agent.id,
- DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
- )
+ end
- expect(classifier[:model]).to eq(llm_model)
+ it "falls back to the newest LLM model" do
+ SiteSetting.ai_default_llm_model = ""
+ SiteSetting.ai_sentiment_model_configs = ""
+ SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_sentiment_agent = agent_without_default_llm.id
+
+ classifier =
+ post_classification.send(
+ :agent_classifier,
+ :sentiment,
+ agent_without_default_llm.id,
+ DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
+ )
+
+ expect(classifier[:model]).to eq(newest_llm_model)
+ end
end
end
@@ -262,8 +246,15 @@ RSpec.describe DiscourseAi::Sentiment::PostClassification do
post_classification.bulk_classify!(Post.where(id: [post_1.id, post_2.id]))
- check_classification_for(post_1)
- check_classification_for(post_2)
+ results =
+ ClassificationResult.where(
+ model_used: "cardiffnlp/twitter-roberta-base-sentiment-latest",
+ target: [post_1, post_2],
+ ).to_a
+ expect(results.map(&:target_id)).to contain_exactly(post_1.id, post_2.id)
+ expect(results.map { |result| result.classification.keys }).to all(
+ contain_exactly("negative", "neutral", "positive"),
+ )
end
it "does nothing if there are no classification model" do
@@ -337,30 +328,37 @@ RSpec.describe DiscourseAi::Sentiment::PostClassification do
expect(posts).to contain_exactly(classified_post)
end
- it "does not reclassify agent results when the agent LLM changes" do
- llm_model = Fabricate(:fake_model)
- ai_agent =
- agent_for(
- %w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
- llm_model,
+ context "with an agent classification" do
+ fab!(:llm_model, :fake_model)
+ fab!(:ai_agent) do
+ Fabricate(
+ :ai_agent,
+ default_llm: llm_model,
+ response_format:
+ %w[negative neutral positive].map { |label| { "key" => label, "type" => "number" } },
+ system_prompt: "Classify this post",
)
- SiteSetting.ai_sentiment_model_configs = ""
- SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
- SiteSetting.ai_sentiment_emotion_classification_strategy = "agent"
- SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
- SiteSetting.ai_sentiment_emotion_agent = "0"
+ end
- classified_post = Fabricate(:post)
- Fabricate(
- :classification_result,
- target: classified_post,
- model_used: DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
- )
+ it "does not reclassify agent results when the agent LLM changes" do
+ SiteSetting.ai_sentiment_model_configs = ""
+ SiteSetting.ai_sentiment_sentiment_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_emotion_classification_strategy = "agent"
+ SiteSetting.ai_sentiment_sentiment_agent = ai_agent.id
+ SiteSetting.ai_sentiment_emotion_agent = "0"
- ai_agent.update!(default_llm: Fabricate(:fake_model, name: "new-model"))
+ classified_post = Fabricate(:post)
+ Fabricate(
+ :classification_result,
+ target: classified_post,
+ model_used: DiscourseAi::Sentiment::Constants::SENTIMENT_AGENT_MODEL,
+ )
- posts = described_class.backfill_query
- expect(posts).to be_empty
+ ai_agent.update!(default_llm: Fabricate(:fake_model, name: "new-model"))
+
+ posts = described_class.backfill_query
+ expect(posts).to be_empty
+ end
end
it "excludes deleted posts" do
diff --git a/plugins/discourse-assign/spec/components/search_spec.rb b/plugins/discourse-assign/spec/components/search_spec.rb
index 586a38f74f8..24a9b89490d 100644
--- a/plugins/discourse-assign/spec/components/search_spec.rb
+++ b/plugins/discourse-assign/spec/components/search_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe Search do
fab!(:user, :active_user)
fab!(:user2, :user)
@@ -22,8 +20,8 @@ describe Search do
let(:post6) { Fabricate(:post) }
before do
- add_to_assign_allowed_group(user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user)
+ assign_allowed_group.add(user2)
Assigner.new(post1.topic, user).assign(user)
Assigner.new(post2.topic, user).assign(user2)
diff --git a/plugins/discourse-assign/spec/components/topic_query_spec.rb b/plugins/discourse-assign/spec/components/topic_query_spec.rb
index b3578b22e8f..f58a970042f 100644
--- a/plugins/discourse-assign/spec/components/topic_query_spec.rb
+++ b/plugins/discourse-assign/spec/components/topic_query_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe TopicQuery do
before { SiteSetting.assign_enabled = true }
@@ -13,8 +11,12 @@ describe TopicQuery do
include_context "with group that is allowed to assign"
before do
- add_to_assign_allowed_group(user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user)
+ assign_allowed_group.add(user2)
+ end
+
+ def assign_to(topic:, user:, assignee:)
+ topic.tap { |assigned_topic| Assigner.new(assigned_topic, user).assign(assignee) }
end
describe "#list_messages_assigned" do
@@ -24,9 +26,9 @@ describe TopicQuery do
fab!(:group_topic) { Fabricate(:post, user: user).topic }
before do
- assign_to(private_message, user, user)
- assign_to(topic, user, user)
- assign_to(group_topic, user, assign_allowed_group)
+ assign_to(topic: private_message, user: user, assignee: user)
+ assign_to(topic: topic, user: user, assignee: user)
+ assign_to(topic: group_topic, user: user, assignee: assign_allowed_group)
end
it "Includes topics and PMs assigned to user" do
@@ -73,9 +75,9 @@ describe TopicQuery do
fab!(:group_topic) { Fabricate(:post, user: user).topic }
before do
- assign_to(private_message, user, user)
- assign_to(topic, user2, user2)
- assign_to(group_topic, user, assign_allowed_group)
+ assign_to(topic: private_message, user: user, assignee: user)
+ assign_to(topic: topic, user: user2, assignee: user2)
+ assign_to(topic: group_topic, user: user, assignee: assign_allowed_group)
end
it "Includes topics and PMs assigned to user" do
@@ -108,7 +110,7 @@ describe TopicQuery do
# Create a new topic with only a post assignment (no topic assignment)
post_only_topic = Fabricate(:post, user: user).topic
post_in_topic = Fabricate(:post, topic: post_only_topic)
- assign_to(post_in_topic, user, user)
+ assign_to(topic: post_in_topic, user: user, assignee: user)
assigned_messages =
TopicQuery.new(user, { page: 0 }).list_group_topics_assigned(assign_allowed_group).topics
@@ -168,7 +170,7 @@ describe TopicQuery do
archetype: Archetype.private_message,
).topic
- assign_to(topic, user, user)
+ assign_to(topic: topic, user: user, assignee: user)
end
let(:group2) { Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone]) }
@@ -181,7 +183,7 @@ describe TopicQuery do
archetype: Archetype.private_message,
).topic
- assign_to(topic, user, user)
+ assign_to(topic: topic, user: user, assignee: user)
end
before do
@@ -285,8 +287,4 @@ describe TopicQuery do
expect(query.topics).to contain_exactly(assigned_topic, unassigned_topic)
end
end
-
- def assign_to(topic, user, assignee)
- topic.tap { |t| Assigner.new(t, user).assign(assignee) }
- end
end
diff --git a/plugins/discourse-assign/spec/components/topics_bulk_action_spec.rb b/plugins/discourse-assign/spec/components/topics_bulk_action_spec.rb
index 22d903992c7..3aeea215f0c 100644
--- a/plugins/discourse-assign/spec/components/topics_bulk_action_spec.rb
+++ b/plugins/discourse-assign/spec/components/topics_bulk_action_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe TopicsBulkAction do
fab!(:post)
fab!(:post1, :post)
@@ -14,7 +12,7 @@ describe TopicsBulkAction do
include_context "with group that is allowed to assign"
- before { add_to_assign_allowed_group(user) }
+ before { assign_allowed_group.add(user) }
describe "assign_topics" do
it "assigns multiple topics to a user" do
diff --git a/plugins/discourse-assign/spec/integration/assign_spec.rb b/plugins/discourse-assign/spec/integration/assign_spec.rb
index c7c9273e2d6..498ea547940 100644
--- a/plugins/discourse-assign/spec/integration/assign_spec.rb
+++ b/plugins/discourse-assign/spec/integration/assign_spec.rb
@@ -1,6 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
require_relative "../fabricators/assign_hook_fabricator"
describe "integration tests" do
@@ -25,8 +24,8 @@ describe "integration tests" do
include_context "with group that is allowed to assign"
before do
- add_to_assign_allowed_group(user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user)
+ assign_allowed_group.add(user2)
group.add(user)
group.add(user2)
pm.topic_allowed_groups.create!(group: group)
@@ -34,8 +33,7 @@ describe "integration tests" do
def assert_publish_topic_state(topic, user: nil, group: nil)
messages = MessageBus.track_publish { yield }
-
- message = messages.find { |m| m.channel == channel }
+ message = messages.find { |published_message| published_message.channel == channel }
expect(message.data[:topic_id]).to eq(topic.id)
expect(message.user_ids).to eq([user.id]) if user
@@ -105,8 +103,8 @@ describe "integration tests" do
include_context "with group that is allowed to assign"
before do
- add_to_assign_allowed_group(user1)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user1)
+ assign_allowed_group.add(user2)
end
it "assigns topic" do
@@ -150,7 +148,7 @@ describe "integration tests" do
include_context "with group that is allowed to assign"
it "allows to assign topic if post is already assigned" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
assigner = Assigner.new(post, user)
response = assigner.assign(user)
diff --git a/plugins/discourse-assign/spec/lib/assigner_spec.rb b/plugins/discourse-assign/spec/lib/assigner_spec.rb
index 4a24c931c04..84225bc05f7 100644
--- a/plugins/discourse-assign/spec/lib/assigner_spec.rb
+++ b/plugins/discourse-assign/spec/lib/assigner_spec.rb
@@ -16,7 +16,7 @@ RSpec.describe Assigner do
let(:secure_category) { Fabricate(:private_category, group: Fabricate(:group)) }
let(:secure_topic) { Fabricate(:post).topic.tap { |t| t.update(category: secure_category) } }
let(:moderator) { Fabricate(:moderator) }
- let(:moderator_2) { Fabricate(:moderator) }
+ fab!(:moderator_2, :moderator)
let(:admin) { Fabricate(:admin) }
let(:assigner) { described_class.new(topic, moderator_2) }
let(:assigner_self) { described_class.new(topic, moderator) }
@@ -161,34 +161,90 @@ RSpec.describe Assigner do
expect(assignment.target).to eq(topic)
end
- it "enqueues assigned workflows matching the assignment target" do
- SiteSetting.enable_discourse_workflows = true
- Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
- DiscourseWorkflows::Registry.reset_indexes!
+ context "with published assignment workflows" do
+ fab!(:all_assignments_workflow) do
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: moderator_2,
+ published: true,
+ nodes: [
+ {
+ "id" => "all-assignments",
+ "type" => "trigger:assigned",
+ "typeVersion" => "1.0",
+ "name" => "All assignments",
+ "position" => {
+ "x" => 0,
+ "y" => 0,
+ },
+ "parameters" => {
+ },
+ "credentials" => {
+ },
+ },
+ ],
+ connections: {
+ },
+ )
+ end
+ fab!(:topic_assignments_workflow) do
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: moderator_2,
+ published: true,
+ nodes: [
+ {
+ "id" => "topic-assignments",
+ "type" => "trigger:assigned",
+ "typeVersion" => "1.0",
+ "name" => "Topic assignments",
+ "position" => {
+ "x" => 0,
+ "y" => 0,
+ },
+ "parameters" => {
+ "topic_assignments_only" => true,
+ },
+ "credentials" => {
+ },
+ },
+ ],
+ connections: {
+ },
+ )
+ end
- create_published_workflow("all-assignments")
- create_published_workflow("topic-assignments", "topic_assignments_only" => true)
+ it "enqueues assigned workflows matching the assignment target" do
+ SiteSetting.enable_discourse_workflows = true
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+ DiscourseWorkflows::Registry.reset_indexes!
- post_assignment_topic = Fabricate(:post).topic
- post_assignment_post = Fabricate(:post, topic: post_assignment_topic)
+ post_assignment_topic = Fabricate(:post).topic
+ post_assignment_post = Fabricate(:post, topic: post_assignment_topic)
- described_class.new(post_assignment_post, moderator_2).assign(moderator)
+ described_class.new(post_assignment_post, moderator_2).assign(moderator)
- expect(enqueued_workflow_trigger_node_ids).to contain_exactly("all-assignments")
+ trigger_node_ids =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map do |job|
+ job["args"].first["trigger_node_id"]
+ end
+ expect(trigger_node_ids).to contain_exactly("all-assignments")
- Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
- described_class.new(topic, moderator_2).assign(moderator)
+ described_class.new(topic, moderator_2).assign(moderator)
- expect(enqueued_workflow_trigger_node_ids).to contain_exactly(
- "all-assignments",
- "topic-assignments",
- )
+ trigger_node_ids =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map do |job|
+ job["args"].first["trigger_node_id"]
+ end
+ expect(trigger_node_ids).to contain_exactly("all-assignments", "topic-assignments")
- trigger_data =
- Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
- expect(trigger_data["assignment"]["target_type"]).to eq("Topic")
- expect(trigger_data["post"]["id"]).to eq(topic.first_post.id)
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data["assignment"]["target_type"]).to eq("Topic")
+ expect(trigger_data["post"]["id"]).to eq(topic.first_post.id)
+ end
end
it "does not update notification level if already watching" do
@@ -247,48 +303,13 @@ RSpec.describe Assigner do
another_mod = Fabricate(:moderator)
Email::Sender.any_instance.expects(:send).once
- expect(assigned_to?(moderator)).to eq(true)
+ expect(assigner.assign(moderator).fetch(:success)).to eq(true)
Email::Sender.any_instance.expects(:send).never
- expect(assigned_to?(moderator)).to eq(false)
+ expect(assigner.assign(moderator).fetch(:success)).to eq(false)
Email::Sender.any_instance.expects(:send).once
- expect(assigned_to?(another_mod)).to eq(true)
- end
-
- def assigned_to?(assignee)
- assigner.assign(assignee).fetch(:success)
- end
-
- def create_published_workflow(trigger_node_id, configuration = {})
- Fabricate(
- :discourse_workflows_workflow,
- created_by: moderator_2,
- published: true,
- nodes: [
- {
- "id" => trigger_node_id,
- "type" => "trigger:assigned",
- "typeVersion" => "1.0",
- "name" => trigger_node_id.humanize,
- "position" => {
- "x" => 0,
- "y" => 0,
- },
- "parameters" => configuration.deep_stringify_keys,
- "credentials" => {
- },
- },
- ],
- connections: {
- },
- )
- end
-
- def enqueued_workflow_trigger_node_ids
- Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map do |job|
- job["args"].first["trigger_node_id"]
- end
+ expect(assigner.assign(another_mod).fetch(:success)).to eq(true)
end
describe "forbidden reasons" do
diff --git a/plugins/discourse-assign/spec/lib/pending_assigns_reminder_spec.rb b/plugins/discourse-assign/spec/lib/pending_assigns_reminder_spec.rb
index d5219bc7026..c2617d3596b 100644
--- a/plugins/discourse-assign/spec/lib/pending_assigns_reminder_spec.rb
+++ b/plugins/discourse-assign/spec/lib/pending_assigns_reminder_spec.rb
@@ -1,14 +1,12 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
-def assert_reminder_not_created
- expect { reminder.remind(user) }.not_to change { Post.count }
-end
-
RSpec.describe PendingAssignsReminder do
subject(:reminder) { described_class.new }
+ def assert_reminder_not_created
+ expect { reminder.remind(user) }.not_to change { Post.count }
+ end
+
before { SiteSetting.assign_enabled = true }
let(:user) { Fabricate(:user) }
@@ -29,22 +27,23 @@ RSpec.describe PendingAssignsReminder do
include_context "with group that is allowed to assign"
+ fab!(:secure_category_group, :group)
+ fab!(:secure_category) { Fabricate(:private_category, group: secure_category_group) }
+ fab!(:first_assigned_post, :post)
+ fab!(:second_assigned_post, :post)
+ fab!(:trashed_assigned_post, :post)
+ fab!(:private_category_assigned_post, :post)
+
before do
- add_to_assign_allowed_group(user)
-
- secure_category = Fabricate(:private_category, group: Fabricate(:group))
-
- @post1 = Fabricate(:post)
- @post2 = Fabricate(:post)
- @post2.topic.update_column(:fancy_title, nil)
- @post3 = Fabricate(:post)
- @post4 = Fabricate(:post)
- Assigner.new(@post1.topic, user).assign(user)
- Assigner.new(@post2.topic, user).assign(user)
- Assigner.new(@post3.topic, user).assign(user)
- Assigner.new(@post4.topic, user).assign(user)
- @post3.topic.trash!
- @post4.topic.update(category: secure_category)
+ assign_allowed_group.add(user)
+
+ second_assigned_post.topic.update_column(:fancy_title, nil)
+ Assigner.new(first_assigned_post.topic, user).assign(user)
+ Assigner.new(second_assigned_post.topic, user).assign(user)
+ Assigner.new(trashed_assigned_post.topic, user).assign(user)
+ Assigner.new(private_category_assigned_post.topic, user).assign(user)
+ trashed_assigned_post.topic.trash!
+ private_category_assigned_post.topic.update(category: secure_category)
end
it "creates a reminder for a particular user and sets the timestamp of the last reminder" do
@@ -61,10 +60,10 @@ RSpec.describe PendingAssignsReminder do
expect(topic.title).to eq(I18n.t("pending_assigns_reminder.title", pending_assignments: 2))
- expect(post.raw).to include(@post1.topic.fancy_title)
- expect(post.raw).to include(@post2.topic.fancy_title)
- expect(post.raw).to_not include(@post3.topic.fancy_title)
- expect(post.raw).to_not include(@post4.topic.fancy_title)
+ expect(post.raw).to include(first_assigned_post.topic.fancy_title)
+ expect(post.raw).to include(second_assigned_post.topic.fancy_title)
+ expect(post.raw).to_not include(trashed_assigned_post.topic.fancy_title)
+ expect(post.raw).to_not include(private_category_assigned_post.topic.fancy_title)
expect(user.reload.custom_fields[described_class::REMINDED_AT].to_datetime).to eq_time(
DateTime.now,
@@ -87,7 +86,7 @@ RSpec.describe PendingAssignsReminder do
it "doesn't delete reminders from a different user" do
reminder.remind(user)
another_user = Fabricate(:user)
- add_to_assign_allowed_group(another_user)
+ assign_allowed_group.add(another_user)
3.times do
post = Fabricate(:post)
Assigner.new(post.topic, user).assign(another_user)
@@ -131,8 +130,8 @@ RSpec.describe PendingAssignsReminder do
post = Post.last
topic = post.topic
expect(topic.title).to eq(I18n.t("pending_assigns_reminder.title", pending_assignments: 2))
- expect(post.raw).to include(@post1.topic.fancy_title)
- expect(post.raw).to include(@post2.topic.fancy_title)
+ expect(post.raw).to include(first_assigned_post.topic.fancy_title)
+ expect(post.raw).to include(second_assigned_post.topic.fancy_title)
expect(post.raw).to_not include(post.topic.fancy_title)
end
@@ -148,8 +147,8 @@ RSpec.describe PendingAssignsReminder do
topic = post.topic
expect(topic.title).to eq(I18n.t("pending_assigns_reminder.title", pending_assignments: 3))
- expect(post.raw).to include(@post1.topic.fancy_title)
- expect(post.raw).to include(@post2.topic.fancy_title)
+ expect(post.raw).to include(first_assigned_post.topic.fancy_title)
+ expect(post.raw).to include(second_assigned_post.topic.fancy_title)
expect(post.raw).to include(pm.fancy_title)
end
@@ -178,12 +177,12 @@ RSpec.describe PendingAssignsReminder do
end
context "with assigns_reminder_assigned_topics_query modifier" do
- let(:modifier_block) { Proc.new { |query| query.where.not(id: @post1.topic_id) } }
it "updates the query correctly" do
+ modifier_block = proc { |query| query.where.not(id: first_assigned_post.topic_id) }
plugin_instance = Plugin::Instance.new
plugin_instance.register_modifier(:assigns_reminder_assigned_topics_query, &modifier_block)
topics = reminder.send(:assigned_topics, user, order: :asc)
- expect(topics).not_to include(@post1.topic)
+ expect(topics).not_to include(first_assigned_post.topic)
ensure
DiscoursePluginRegistry.unregister_modifier(
plugin_instance,
@@ -194,8 +193,8 @@ RSpec.describe PendingAssignsReminder do
end
context "with assigned_count_for_user_query modifier" do
- let(:modifier_block) { Proc.new { |query, user| query.where.not(assigned_to_id: user.id) } }
it "updates the query correctly" do
+ modifier_block = proc { |query, user| query.where.not(assigned_to_id: user.id) }
expect(reminder.send(:assigned_count_for, user)).to eq(2)
plugin_instance = Plugin::Instance.new
diff --git a/plugins/discourse-assign/spec/lib/random_assign_utils_spec.rb b/plugins/discourse-assign/spec/lib/random_assign_utils_spec.rb
index b45cb2e21a5..a5b10577002 100644
--- a/plugins/discourse-assign/spec/lib/random_assign_utils_spec.rb
+++ b/plugins/discourse-assign/spec/lib/random_assign_utils_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
RSpec.describe RandomAssignUtils do
FakeAutomation = Struct.new(:id)
diff --git a/plugins/discourse-assign/spec/requests/assign_controller_spec.rb b/plugins/discourse-assign/spec/requests/assign_controller_spec.rb
index 562c53c7bf9..2630f7cde35 100644
--- a/plugins/discourse-assign/spec/requests/assign_controller_spec.rb
+++ b/plugins/discourse-assign/spec/requests/assign_controller_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
RSpec.describe DiscourseAssign::AssignController do
before do
SiteSetting.assign_enabled = true
@@ -50,6 +48,12 @@ RSpec.describe DiscourseAssign::AssignController do
describe "#suggestions" do
before { sign_in(admin) }
+ def assign_user_to_post
+ assignee = Fabricate(:user, groups: [allowed_group])
+ Fabricate(:post_assignment, assigned_to: assignee, assigned_by_user: admin)
+ assignee
+ end
+
it "only includes users in allowed groups and not disallowed groups" do
Assigner.new(post.topic, admin).assign(allowed_user)
@@ -133,12 +137,6 @@ RSpec.describe DiscourseAssign::AssignController do
scoped_group.name,
)
end
-
- def assign_user_to_post
- assignee = Fabricate(:user, groups: [allowed_group])
- Fabricate(:post_assignment, assigned_to: assignee, assigned_by_user: admin)
- assignee
- end
end
describe "#unassign" do
@@ -212,7 +210,7 @@ RSpec.describe DiscourseAssign::AssignController do
restricted_group = Fabricate(:group)
private_category = Fabricate(:private_category, group: restricted_group)
private_topic = Fabricate(:topic, category: private_category)
- add_to_assign_allowed_group(allowed_user)
+ assign_allowed_group.add(allowed_user)
sign_in(allowed_user)
@@ -227,7 +225,7 @@ RSpec.describe DiscourseAssign::AssignController do
it "returns 404 when the acting user cannot see the target PM" do
pm_topic = Fabricate(:private_message_topic)
- add_to_assign_allowed_group(allowed_user)
+ assign_allowed_group.add(allowed_user)
sign_in(allowed_user)
@@ -390,7 +388,7 @@ RSpec.describe DiscourseAssign::AssignController do
it "fails to assign topic to the user if they already reached the max assigns limit" do
another_user = Fabricate(:user)
- add_to_assign_allowed_group(another_user)
+ assign_allowed_group.add(another_user)
another_post = Fabricate(:post)
max_assigns = 1
SiteSetting.max_assigned_topics = max_assigns
@@ -416,7 +414,7 @@ RSpec.describe DiscourseAssign::AssignController do
it "fails with a specific error message if the topic is a PM and the assignee can not see it" do
pm = Fabricate(:private_message_post, user: admin).topic
another_user = Fabricate(:user)
- add_to_assign_allowed_group(another_user)
+ assign_allowed_group.add(another_user)
put "/assign/assign.json",
params: {
target_id: pm.id,
@@ -494,7 +492,7 @@ RSpec.describe DiscourseAssign::AssignController do
it "fails with a specific error message if the topic is not a PM and the assignee can not see it" do
topic = Fabricate(:topic, category: Fabricate(:private_category, group: Fabricate(:group)))
another_user = Fabricate(:user)
- add_to_assign_allowed_group(another_user)
+ assign_allowed_group.add(another_user)
put "/assign/assign.json",
params: {
target_id: topic.id,
diff --git a/plugins/discourse-assign/spec/requests/list_controller_spec.rb b/plugins/discourse-assign/spec/requests/list_controller_spec.rb
index aedd05068a1..2a196a334e0 100644
--- a/plugins/discourse-assign/spec/requests/list_controller_spec.rb
+++ b/plugins/discourse-assign/spec/requests/list_controller_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe ListController do
before do
SiteSetting.personal_message_enabled_groups = Group::AUTO_GROUPS[:trust_level_0]
@@ -20,7 +18,7 @@ describe ListController do
sign_in(user)
SiteSetting.assign_allowed_on_groups = ""
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
expect(response.status).to eq(403)
get "/topics/messages-assigned/#{user.username_lower}.json"
@@ -44,7 +42,7 @@ describe ListController do
end
it "as an anon user" do
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
expect(response.status).to eq(403)
get "/topics/messages-assigned/#{user.username_lower}.json"
@@ -53,7 +51,7 @@ describe ListController do
it "as an admin user" do
sign_in(admin)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
expect(response.status).to eq(200)
get "/topics/messages-assigned/#{user.username_lower}.json"
@@ -72,7 +70,7 @@ describe ListController do
fab!(:topic2) { post2.topic }
before do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic1, user).assign(user)
Assigner.new(topic2, user).assign(user2)
@@ -96,7 +94,7 @@ describe ListController do
end
it "returns user-assigned-topics-list of users in the assigned_allowed_group and doesn't include deleted topic" do
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
expect(
JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["assigned_to_user"]["id"] },
).to match_array([user.id])
@@ -105,13 +103,13 @@ describe ListController do
it "returns user-assigned-topics-list of users in the assigned_allowed_group and doesn't include inactive topics" do
Assignment.where(assigned_to: user, target: topic1).update_all(active: false)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
expect(response.parsed_body["topic_list"]["topics"]).to be_empty
end
it "returns empty user-assigned-topics-list for users not in the assigned_allowed_group" do
ids = []
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
JSON.parse(response.body)["topic_list"]["topics"].each do |t|
ids.push(t["assigned_to_user"]["id"]) if t["assigned_to_user"]["id"] == user2.id
end
@@ -146,7 +144,7 @@ describe ListController do
topic.reload
id = 0
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json"
JSON.parse(response.body)["topic_list"]["topics"].each do |t|
id = t.id if t["id"] == topic.id
@@ -167,8 +165,8 @@ describe ListController do
fab!(:topic3) { post3.topic }
before do
- add_to_assign_allowed_group(user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user)
+ assign_allowed_group.add(user2)
Assigner.new(post1.topic, user).assign(user)
Assigner.new(post2.topic, user).assign(user2)
@@ -194,32 +192,32 @@ describe ListController do
topic2.save!
topic3.save!
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json?order=posts"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json?order=posts"
expect(JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["id"] }).to match_array(
[topic2.id, topic1.id, topic3.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json?order=views"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json?order=views"
expect(JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["id"] }).to match_array(
[topic3.id, topic1.id, topic2.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json?order=activity"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json?order=activity"
expect(JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["id"] }).to match_array(
[topic3.id, topic2.id, topic1.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json?order=posts&ascending=true"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json?order=posts&ascending=true"
expect(JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["id"] }).to match_array(
[topic3.id, topic1.id, topic2.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json?order=views&ascending=true"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json?order=views&ascending=true"
expect(JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["id"] }).to match_array(
[topic2.id, topic1.id, topic3.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json?order=activity&ascending=true"
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json?order=activity&ascending=true"
expect(JSON.parse(response.body)["topic_list"]["topics"].map { |t| t["id"] }).to match_array(
[topic1.id, topic2.id, topic3.id],
)
@@ -283,8 +281,8 @@ describe ListController do
before do
SearchIndexer.enable
- add_to_assign_allowed_group(user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user)
+ assign_allowed_group.add(user2)
Assigner.new(post1.topic, user).assign(user)
Assigner.new(post2.topic, user).assign(user2)
@@ -304,7 +302,7 @@ describe ListController do
topic2.save!
topic3.save!
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json",
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json",
params: {
search: "Testing",
}
@@ -312,7 +310,7 @@ describe ListController do
[topic1.id, topic2.id, topic3.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json",
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json",
params: {
search: "RSpec",
}
@@ -320,7 +318,7 @@ describe ListController do
[topic2.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json",
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json",
params: {
search: "love",
}
@@ -343,7 +341,7 @@ describe ListController do
[topic1.id, topic3.id],
)
- get "/topics/group-topics-assigned/#{get_assigned_allowed_group_name}.json",
+ get "/topics/group-topics-assigned/#{assign_allowed_group.name}.json",
params: {
search: "love",
}
@@ -360,7 +358,7 @@ describe ListController do
fab!(:post2, :post)
before do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(post1.topic, user).assign(user)
Assigner.new(post2.topic, user).assign(user2)
@@ -387,10 +385,10 @@ describe ListController do
fab!(:topic) { Fabricate(:topic, user: user) }
fab!(:pm_post) { Fabricate(:post, topic: pm) }
fab!(:post) { Fabricate(:post, topic: topic) }
+ fab!(:private_message_allowed_user) { Fabricate(:topic_allowed_user, user: user, topic: pm) }
before do
SiteSetting.assign_allowed_on_groups = "#{group.id}"
- Fabricate(:topic_allowed_user, user: user, topic: pm)
Assigner.new(pm, user).assign(user)
Assigner.new(topic, user).assign(user)
end
@@ -419,7 +417,7 @@ describe ListController do
describe "when user cannot assign" do
it "ignores the assign filter" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic_1, user).assign(user)
@@ -436,7 +434,7 @@ describe ListController do
before { sign_in(admin) }
it "filters topics by assigned user" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic_1, admin).assign(user)
@@ -460,9 +458,9 @@ describe ListController do
end
it "filters topics by multiple assigned users and groups" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
user2 = Fabricate(:user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user2)
# Assign topics to different users and groups
Assigner.new(topic_1, admin).assign(user)
@@ -483,9 +481,9 @@ describe ListController do
end
it "filters topics by subset of multiple assigned users and groups" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
user2 = Fabricate(:user)
- add_to_assign_allowed_group(user2)
+ assign_allowed_group.add(user2)
# Assign topics to different users and groups
Assigner.new(topic_1, admin).assign(user)
@@ -506,7 +504,7 @@ describe ListController do
end
it "filters topics by assigned:*" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic_1, admin).assign(user)
Assigner.new(topic_2, admin).assign(group)
@@ -521,7 +519,7 @@ describe ListController do
end
it "filters topics by assigned:nobody" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic_1, admin).assign(user)
Assigner.new(topic_2, admin).assign(group)
@@ -536,7 +534,7 @@ describe ListController do
end
it "handles empty multi-value assigned filter gracefully" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic_1, admin).assign(user)
@@ -550,7 +548,7 @@ describe ListController do
end
it "handles non-existent users and groups in multi-value filter" do
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
Assigner.new(topic_1, admin).assign(user)
@@ -570,7 +568,7 @@ describe ListController do
describe "when user cannot assign" do
it "ignores the assigned:* filter" do
- add_to_assign_allowed_group(admin)
+ assign_allowed_group.add(admin)
Assigner.new(topic_1, admin).assign(admin)
@@ -583,7 +581,7 @@ describe ListController do
end
it "ignores the assigned:nobody filter" do
- add_to_assign_allowed_group(admin)
+ assign_allowed_group.add(admin)
Assigner.new(topic_1, admin).assign(admin)
diff --git a/plugins/discourse-assign/spec/requests/topics_bulk_assign_spec.rb b/plugins/discourse-assign/spec/requests/topics_bulk_assign_spec.rb
index 7e7c3d7ad96..d995e027135 100644
--- a/plugins/discourse-assign/spec/requests/topics_bulk_assign_spec.rb
+++ b/plugins/discourse-assign/spec/requests/topics_bulk_assign_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
RSpec.describe TopicsController do
include_context "with group that is allowed to assign"
@@ -13,12 +11,12 @@ RSpec.describe TopicsController do
before do
SiteSetting.assign_enabled = true
SiteSetting.enable_assign_status = true
- add_to_assign_allowed_group(actor)
+ assign_allowed_group.add(actor)
sign_in(actor)
end
def bulk_assign(operation, ids: [topic1.id, topic2.id])
- put "/topics/bulk.json", params: { topic_ids: ids, operation: operation }
+ put "/topics/bulk.json", params: { topic_ids: ids, operation: }
end
describe "#bulk with the assign operation" do
@@ -88,7 +86,7 @@ RSpec.describe TopicsController do
end
it "returns the per-topic failures alongside the topics that succeeded" do
- add_to_assign_allowed_group(allowed_user)
+ assign_allowed_group.add(allowed_user)
private_group = Fabricate(:group, users: [actor])
hidden_topic = Fabricate(:topic, category: Fabricate(:private_category, group: private_group))
diff --git a/plugins/discourse-assign/spec/serializers/flagged_topic_serializer_spec.rb b/plugins/discourse-assign/spec/serializers/flagged_topic_serializer_spec.rb
index 5175033be20..7b7a4eb4057 100644
--- a/plugins/discourse-assign/spec/serializers/flagged_topic_serializer_spec.rb
+++ b/plugins/discourse-assign/spec/serializers/flagged_topic_serializer_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe FlaggedTopicSerializer do
fab!(:user)
let(:guardian) { Guardian.new(user) }
@@ -10,7 +8,7 @@ describe FlaggedTopicSerializer do
before do
SiteSetting.assign_enabled = true
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
end
context "when there are no assignments" do
diff --git a/plugins/discourse-assign/spec/serializers/post_serializer_spec.rb b/plugins/discourse-assign/spec/serializers/post_serializer_spec.rb
index 0162ef7deec..31a12fbaf52 100644
--- a/plugins/discourse-assign/spec/serializers/post_serializer_spec.rb
+++ b/plugins/discourse-assign/spec/serializers/post_serializer_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe PostSerializer do
fab!(:user)
fab!(:topic)
@@ -12,7 +10,7 @@ describe PostSerializer do
before do
SiteSetting.assign_enabled = true
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
end
it "includes assigned user in serializer" do
diff --git a/plugins/discourse-assign/spec/serializers/topic_list_serializer_spec.rb b/plugins/discourse-assign/spec/serializers/topic_list_serializer_spec.rb
index 32b4cad94ba..37499f0de7f 100644
--- a/plugins/discourse-assign/spec/serializers/topic_list_serializer_spec.rb
+++ b/plugins/discourse-assign/spec/serializers/topic_list_serializer_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
RSpec.describe TopicListSerializer do
fab!(:user)
@@ -35,7 +33,7 @@ RSpec.describe TopicListSerializer do
before do
SiteSetting.assign_enabled = true
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
end
describe "#assigned_messages_count" do
diff --git a/plugins/discourse-assign/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-assign/spec/serializers/topic_view_serializer_spec.rb
index 147ec200595..d966b0fd573 100644
--- a/plugins/discourse-assign/spec/serializers/topic_view_serializer_spec.rb
+++ b/plugins/discourse-assign/spec/serializers/topic_view_serializer_spec.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
RSpec.describe TopicViewSerializer do
fab!(:user)
fab!(:topic)
@@ -12,7 +10,7 @@ RSpec.describe TopicViewSerializer do
before do
SiteSetting.assign_enabled = true
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
end
it "includes assigned user in serializer" do
diff --git a/plugins/discourse-assign/spec/serializers/user_bookmark_base_serializer_spec.rb b/plugins/discourse-assign/spec/serializers/user_bookmark_base_serializer_spec.rb
index 6517e58676a..5636ed51ae9 100644
--- a/plugins/discourse-assign/spec/serializers/user_bookmark_base_serializer_spec.rb
+++ b/plugins/discourse-assign/spec/serializers/user_bookmark_base_serializer_spec.rb
@@ -1,13 +1,11 @@
# frozen_string_literal: true
-require_relative "../support/assign_allowed_group"
-
describe UserBookmarkBaseSerializer do
include_context "with group that is allowed to assign"
before do
SiteSetting.assign_enabled = true
- add_to_assign_allowed_group(user)
+ assign_allowed_group.add(user)
end
fab!(:user)
diff --git a/plugins/discourse-assign/spec/support/assign_allowed_group.rb b/plugins/discourse-assign/spec/support/assign_allowed_group.rb
index 2cc249e03e9..82b365c18f6 100644
--- a/plugins/discourse-assign/spec/support/assign_allowed_group.rb
+++ b/plugins/discourse-assign/spec/support/assign_allowed_group.rb
@@ -6,16 +6,4 @@ shared_context "with group that is allowed to assign" do
end
before { SiteSetting.assign_allowed_on_groups += "|#{assign_allowed_group.id}" }
-
- def add_to_assign_allowed_group(user)
- assign_allowed_group.add(user)
- end
-
- def get_assigned_allowed_group
- assign_allowed_group
- end
-
- def get_assigned_allowed_group_name
- assign_allowed_group.name
- end
end
diff --git a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb
index 341387f8c41..f4781d085b7 100644
--- a/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb
+++ b/plugins/discourse-calendar/spec/lib/discourse_post_event/event_parser_spec.rb
@@ -1,14 +1,14 @@
# frozen_string_literal: true
-def build_post(user, raw)
- Post.new(user: user, raw: raw)
-end
-
describe DiscoursePostEvent::EventParser do
subject(:parser) { DiscoursePostEvent::EventParser }
let(:user) { Fabricate(:user) }
+ def build_post(user, raw)
+ Post.new(user:, raw:)
+ end
+
it "works with no event" do
events = parser.extract_events(build_post(user, "this could be a nice event"))
expect(events.length).to eq(0)
diff --git a/plugins/discourse-data-explorer/spec/system/param_input_spec.rb b/plugins/discourse-data-explorer/spec/system/param_input_spec.rb
index eaeb7d695d7..de91271fb25 100644
--- a/plugins/discourse-data-explorer/spec/system/param_input_spec.rb
+++ b/plugins/discourse-data-explorer/spec/system/param_input_spec.rb
@@ -72,11 +72,23 @@ RSpec.describe "Param input" do
ignore_fields = %i[user_id post_id topic_id category_id group_id group_list user_list]
if param.default.present? && ignore_fields.exclude?(param.type)
- expect(page).to have_field(
- param.identifier,
- with: simple_normalize(param.type, param.default),
- visible: :all,
- )
+ normalized_default =
+ case param.type
+ when :date
+ param.default.to_date.to_s
+ when :time
+ param.default.to_time.strftime("%H:%M")
+ when :datetime
+ param.default.to_datetime.strftime("%Y-%m-%dT%H:%M")
+ when :boolean
+ param.default == "#null" ? "#null" : param.default ? "on" : "off"
+ when :boolean_three
+ param.default == "#null" ? "#null" : param.default ? "Y" : "N"
+ else
+ param.default.to_s
+ end
+
+ expect(page).to have_field(param.identifier, with: normalized_default, visible: :all)
end
end
end
@@ -153,20 +165,3 @@ RSpec.describe "Param input" do
end
end
end
-
-def simple_normalize(type, value)
- case type
- when :date
- value.to_date.to_s
- when :time
- value.to_time.strftime("%H:%M")
- when :datetime
- value.to_datetime.strftime("%Y-%m-%dT%H:%M")
- when :boolean
- value == "#null" ? "#null" : value ? "on" : "off"
- when :boolean_three
- value == "#null" ? "#null" : value ? "Y" : "N"
- else
- value.to_s
- end
-end
diff --git a/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb b/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb
index 8c6697d719b..2e8132078da 100644
--- a/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb
+++ b/plugins/discourse-data-explorer/spec/tasks/fix_query_ids_spec.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
describe "fix query ids rake task" do
+ subject(:run_task) { Rake::Task["data_explorer:fix_query_ids"].invoke }
+
before do
Rake::Task.clear
silence_warnings { Discourse::Application.load_tasks }
@@ -10,57 +12,61 @@ describe "fix query ids rake task" do
it "fixes the ID of the query if they share the same name" do
original_query_id = 4
- create_plugin_store_row(query_name, original_query_id)
- create_query(query_name)
+ create_plugin_store_row(name: query_name, id: original_query_id)
+ create_query(name: query_name)
run_task
- expect(find(query_name).id).to eq(original_query_id)
+ expect(DiscourseDataExplorer::Query.find_by(name: query_name).id).to eq(original_query_id)
end
it "only fixes queries with unique name" do
original_query_id = 4
- create_plugin_store_row(query_name, original_query_id)
- create_query(query_name)
- create_query(query_name)
+ create_plugin_store_row(name: query_name, id: original_query_id)
+ create_query(name: query_name)
+ create_query(name: query_name)
run_task
- expect(find(query_name).id).not_to eq(original_query_id)
+ expect(DiscourseDataExplorer::Query.find_by(name: query_name).id).not_to eq(original_query_id)
end
it "skips queries that already have the same ID" do
- db_query = create_query(query_name)
+ db_query = create_query(name: query_name)
last_updated_at = db_query.updated_at
- create_plugin_store_row(query_name, db_query.id)
+ create_plugin_store_row(name: query_name, id: db_query.id)
run_task
- expect(find(query_name).updated_at).to eq_time(last_updated_at)
+ expect(DiscourseDataExplorer::Query.find_by(name: query_name).updated_at).to eq_time(
+ last_updated_at,
+ )
end
it "keeps queries the rest of the queries" do
original_query_id = 4
different_query_name = "Another query"
- create_plugin_store_row(query_name, original_query_id)
- create_query(query_name)
- create_query(different_query_name)
+ create_plugin_store_row(name: query_name, id: original_query_id)
+ create_query(name: query_name)
+ create_query(name: different_query_name)
run_task
- expect(find(different_query_name)).not_to be_nil
+ expect(DiscourseDataExplorer::Query.find_by(name: different_query_name)).not_to be_nil
end
it "works even if they are additional conflicts" do
different_query_name = "Another query"
- additional_conflict = create_query(different_query_name)
- create_query(query_name)
- create_plugin_store_row(query_name, additional_conflict.id)
+ additional_conflict = create_query(name: different_query_name)
+ create_query(name: query_name)
+ create_plugin_store_row(name: query_name, id: additional_conflict.id)
run_task
- expect(find(different_query_name).id).not_to eq(additional_conflict.id)
- expect(find(query_name).id).to eq(additional_conflict.id)
+ expect(DiscourseDataExplorer::Query.find_by(name: different_query_name).id).not_to eq(
+ additional_conflict.id,
+ )
+ expect(DiscourseDataExplorer::Query.find_by(name: query_name).id).to eq(additional_conflict.id)
end
describe "query groups" do
@@ -68,70 +74,60 @@ describe "fix query ids rake task" do
it "fixes the query group's query_id" do
original_query_id = 4
- create_query(query_name, [group.id])
- create_plugin_store_row(query_name, original_query_id, [group.id])
+ create_query(name: query_name, group_ids: [group.id])
+ create_plugin_store_row(name: query_name, id: original_query_id, group_ids: [group.id])
run_task
- expect(find_query_group(original_query_id)).not_to be_nil
+ expect(DiscourseDataExplorer::QueryGroup.find_by(query_id: original_query_id)).not_to be_nil
end
it "works with additional conflicts" do
different_query_name = "Another query"
- additional_conflict = create_query(different_query_name, [group.id])
- create_query(query_name, [group.id])
- create_plugin_store_row(query_name, additional_conflict.id, [group.id])
+ additional_conflict = create_query(name: different_query_name, group_ids: [group.id])
+ create_query(name: query_name, group_ids: [group.id])
+ create_plugin_store_row(name: query_name, id: additional_conflict.id, group_ids: [group.id])
run_task
- conflict = find(different_query_name).query_groups.first
- fixed = find_query_group(additional_conflict.id)
+ conflict = DiscourseDataExplorer::Query.find_by(name: different_query_name).query_groups.first
+ fixed = DiscourseDataExplorer::QueryGroup.find_by(query_id: additional_conflict.id)
expect(conflict.query_id).not_to eq(additional_conflict.id)
expect(fixed.query_id).to eq(additional_conflict.id)
end
-
- def find_query_group(id)
- DiscourseDataExplorer::QueryGroup.find_by(query_id: id)
- end
end
it "changes the serial sequence for future queries" do
original_query_id = 4
- create_plugin_store_row(query_name, original_query_id)
- create_query(query_name)
+ create_plugin_store_row(name: query_name, id: original_query_id)
+ create_query(name: query_name)
run_task
- post_fix_query = create_query(query_name)
+ post_fix_query = create_query(name: query_name)
expect(post_fix_query.id).to eq(original_query_id + 1)
end
- def run_task
- Rake::Task["data_explorer:fix_query_ids"].invoke
- end
-
- def create_plugin_store_row(name, id, group_ids = [])
- key = "q:#{id}"
-
+ def create_plugin_store_row(name:, id:, group_ids: [])
PluginStore.set(
DiscourseDataExplorer::PLUGIN_NAME,
- key,
- attributes(name).merge(group_ids: group_ids, id: id),
+ "q:#{id}",
+ attributes(name:).merge(group_ids:, id:),
)
end
- def create_query(name, group_ids = [])
+ def create_query(name:, group_ids: [])
DiscourseDataExplorer::Query
- .create!(attributes(name))
- .tap { |query| group_ids.each { |group_id| query.query_groups.create!(group_id: group_id) } }
+ .create!(attributes(name:))
+ .tap { |query| group_ids.each { |group_id| query.query_groups.create!(group_id:) } }
end
- def attributes(name)
+ def attributes(name:)
{
id:
DiscourseDataExplorer::Query.count == 0 ? 5 : DiscourseDataExplorer::Query.maximum(:id) + 1,
- name: name,
+ name:,
description: "A Query",
sql: "SELECT 1",
created_at: 3.hours.ago,
@@ -139,8 +135,4 @@ describe "fix query ids rake task" do
hidden: false,
}
end
-
- def find(name)
- DiscourseDataExplorer::Query.find_by(name: name)
- end
end
diff --git a/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb b/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb
index 2183d91a172..baa847665c2 100644
--- a/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/update_scores_for_ten_days_spec.rb
@@ -1,16 +1,14 @@
# frozen_string_literal: true
describe Jobs::UpdateScoresForTenDays do
+ subject(:run_job) { described_class.new.execute }
+
fab!(:user)
fab!(:user_2, :user)
fab!(:leaderboard, :gamification_leaderboard)
let!(:topic_user_created) { Fabricate(:topic, user: user) }
let!(:topic_user_2_created) { Fabricate(:topic, user: user_2) }
- def run_job
- described_class.new.execute
- end
-
before do
SiteSetting.discourse_gamification_enabled = true
topic_user_created.update(created_at: 8.days.ago)
diff --git a/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb b/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb
index dd55cdbf8ba..b7ae01ab366 100644
--- a/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb
+++ b/plugins/discourse-gamification/spec/jobs/update_scores_for_today_spec.rb
@@ -1,6 +1,8 @@
# frozen_string_literal: true
describe Jobs::UpdateScoresForToday do
+ subject(:run_job) { described_class.new.execute }
+
fab!(:user)
fab!(:user_2, :user)
fab!(:post) { Fabricate(:post, user: user, post_number: 2) }
@@ -12,10 +14,6 @@ describe Jobs::UpdateScoresForToday do
let(:leaderboard_1_positions) { DiscourseGamification::LeaderboardCachedView.new(leaderboard_1) }
let(:leaderboard_2_positions) { DiscourseGamification::LeaderboardCachedView.new(leaderboard_2) }
- def run_job
- described_class.new.execute
- end
-
before do
SiteSetting.discourse_gamification_enabled = true
topic_user_2_created.update(created_at: 2.days.ago)
diff --git a/plugins/discourse-local-dates/spec/lib/pretty_text_spec.rb b/plugins/discourse-local-dates/spec/lib/pretty_text_spec.rb
index a75d091b255..971cca9961b 100644
--- a/plugins/discourse-local-dates/spec/lib/pretty_text_spec.rb
+++ b/plugins/discourse-local-dates/spec/lib/pretty_text_spec.rb
@@ -1,19 +1,5 @@
# frozen_string_literal: true
-def generate_html(text, opts = {})
- output = "<p><span"
- output += " class=\"discourse-local-date\""
- output += " data-date=\"#{opts[:date]}\"" if opts[:date]
- output += " data-email-preview=\"#{opts[:email_preview]}\"" if opts[:email_preview]
- output += " data-format=\"#{opts[:format]}\"" if opts[:format]
- output += " data-time=\"#{opts[:time]}\"" if opts[:time]
- output += " data-timezone=\"#{opts[:timezone]}\"" if opts[:timezone]
- output += " data-timezones=\"#{opts[:timezones]}\"" if opts[:timezones]
- output += ">"
- output += text
- output + "</span></p>"
-end
-
RSpec.describe PrettyText do
before { freeze_time }
@@ -22,11 +8,7 @@ RSpec.describe PrettyText do
SiteSetting.discourse_local_dates_email_format = "YYYY-MM-DDTHH:mm:ss[Z] z"
cooked = PrettyText.cook("[date=2018-05-08]")
cooked_mail =
- generate_html(
- "2018-05-08T00:00:00Z UTC",
- date: "2018-05-08",
- email_preview: "2018-05-08T00:00:00Z UTC",
- )
+ '<p><span class="discourse-local-date" data-date="2018-05-08" data-email-preview="2018-05-08T00:00:00Z UTC">2018-05-08T00:00:00Z UTC</span></p>'
expect(PrettyText.format_for_email(cooked)).to match_html(cooked_mail)
end
@@ -35,12 +17,7 @@ RSpec.describe PrettyText do
SiteSetting.discourse_local_dates_email_format = "YYYY-MM-DDTHH:mm:ss[Z] UTC"
cooked = PrettyText.cook("[date=2018-05-08 time=20:00:00]")
cooked_mail =
- generate_html(
- "2018-05-08T20:00:00Z UTC",
- date: "2018-05-08",
- email_preview: "2018-05-08T20:00:00Z UTC",
- time: "20:00:00",
- )
+ '<p><span class="discourse-local-date" data-date="2018-05-08" data-email-preview="2018-05-08T20:00:00Z UTC" data-time="20:00:00">2018-05-08T20:00:00Z UTC</span></p>'
expect(PrettyText.format_for_email(cooked)).to match_html(cooked_mail)
end
@@ -52,13 +29,7 @@ RSpec.describe PrettyText do
'[date=2023-05-08 timezone="Europe/Paris" timezones="America/Los_Angeles|Pacific/Auckland"]',
)
cooked_mail =
- generate_html(
- "2023-05-07T22:00:00Z UTC",
- date: "2023-05-08",
- email_preview: "2023-05-07T22:00:00Z UTC",
- timezone: "Europe/Paris",
- timezones: "America/Los_Angeles|Pacific/Auckland",
- )
+ '<p><span class="discourse-local-date" data-date="2023-05-08" data-email-preview="2023-05-07T22:00:00Z UTC" data-timezone="Europe/Paris" data-timezones="America/Los_Angeles|Pacific/Auckland">2023-05-07T22:00:00Z UTC</span></p>'
expect(PrettyText.format_for_email(cooked)).to match_html(cooked_mail)
end
@@ -73,11 +44,7 @@ RSpec.describe PrettyText do
cooked = PrettyText.cook("[date=2018-05-08]")
cooked_mail =
- generate_html(
- "Tue, May 8, 2018 2:00 AM",
- date: "2018-05-08",
- email_preview: "Tue, May 8, 2018 2:00 AM",
- )
+ '<p><span class="discourse-local-date" data-date="2018-05-08" data-email-preview="Tue, May 8, 2018 2:00 AM">Tue, May 8, 2018 2:00 AM</span></p>'
expect(PrettyText.format_for_email(cooked)).to match_html(cooked_mail)
end
@@ -88,7 +55,8 @@ RSpec.describe PrettyText do
it "uses the site setting" do
cooked = PrettyText.cook("[date=2018-05-08]")
- cooked_mail = generate_html("08/05 UTC", date: "2018-05-08", email_preview: "08/05 UTC")
+ cooked_mail =
+ '<p><span class="discourse-local-date" data-date="2018-05-08" data-email-preview="08/05 UTC">08/05 UTC</span></p>'
expect(PrettyText.format_for_email(cooked)).to match_html(cooked_mail)
end
diff --git a/plugins/discourse-microsoft-auth/spec/integration/microsoft_auth_spec.rb b/plugins/discourse-microsoft-auth/spec/integration/microsoft_auth_spec.rb
index a99be4e3c05..e282ff91a9d 100644
--- a/plugins/discourse-microsoft-auth/spec/integration/microsoft_auth_spec.rb
+++ b/plugins/discourse-microsoft-auth/spec/integration/microsoft_auth_spec.rb
@@ -8,33 +8,6 @@ describe "Microsoft OAuth2" do
fab!(:user1, :user)
- def setup_ms_emails_stub(email:)
- stub_request(:get, "https://graph.microsoft.com/v1.0/me").with(
- headers: {
- "Authorization" => "Bearer #{access_token}",
- },
- ).to_return(
- status: 200,
- body:
- JSON.dump(
- businessPhones: ["+1 425 555 0109"],
- displayName: "Adele Vance",
- givenName: "Adele",
- jobTitle: "Retail Manager",
- mail: email,
- mobilePhone: "+1 425 555 0109",
- officeLocation: "18/2111",
- preferredLanguage: "en-US",
- surname: "Vance",
- userPrincipalName: email,
- id: "87d349ed-44d7-43e1-9a83-5f2406dee5bd",
- ),
- headers: {
- "Content-Type" => "application/json",
- },
- )
- end
-
before do
SiteSetting.microsoft_auth_enabled = true
SiteSetting.microsoft_auth_client_id = client_id
@@ -62,6 +35,31 @@ describe "Microsoft OAuth2" do
"Content-Type" => "application/x-www-form-urlencoded",
},
)
+
+ stub_request(:get, "https://graph.microsoft.com/v1.0/me").with(
+ headers: {
+ "Authorization" => "Bearer #{access_token}",
+ },
+ ).to_return(
+ status: 200,
+ body:
+ JSON.dump(
+ businessPhones: ["+1 425 555 0109"],
+ displayName: "Adele Vance",
+ givenName: "Adele",
+ jobTitle: "Retail Manager",
+ mail: user1.email,
+ mobilePhone: "+1 425 555 0109",
+ officeLocation: "18/2111",
+ preferredLanguage: "en-US",
+ surname: "Vance",
+ userPrincipalName: user1.email,
+ id: "87d349ed-44d7-43e1-9a83-5f2406dee5bd",
+ ),
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
end
it "signs in the user whose email matches the email included in the API response from microsoft when `microsoft_auth_email_verified` site setting is true" do
@@ -74,8 +72,6 @@ describe "Microsoft OAuth2" do
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
)
- setup_ms_emails_stub(email: user1.email)
-
post "/auth/microsoft_office365/callback",
params: {
state: session["omniauth.state"],
@@ -97,8 +93,6 @@ describe "Microsoft OAuth2" do
"https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
)
- setup_ms_emails_stub(email: user1.email)
-
post "/auth/microsoft_office365/callback",
params: {
state: session["omniauth.state"],
diff --git a/plugins/discourse-narrative-bot/spec/discourse_narrative_bot/quote_generator_spec.rb b/plugins/discourse-narrative-bot/spec/discourse_narrative_bot/quote_generator_spec.rb
index 52c2e778086..3d0d9d975bc 100644
--- a/plugins/discourse-narrative-bot/spec/discourse_narrative_bot/quote_generator_spec.rb
+++ b/plugins/discourse-narrative-bot/spec/discourse_narrative_bot/quote_generator_spec.rb
@@ -3,26 +3,26 @@
RSpec.describe DiscourseNarrativeBot::QuoteGenerator do
fab!(:user)
- def bundled_quotes(locale)
- I18n.with_locale(locale) do
+ let(:bundled_quotes) do
+ I18n.with_locale(user.effective_locale) do
I18n
.t("discourse_narrative_bot.quote")
.values
- .select { |v| v.is_a?(Hash) }
- .map { |q| described_class.format_quote(q[:quote], q[:author]) }
+ .select { |quote| quote.is_a?(Hash) }
+ .map { |quote| described_class.format_quote(quote[:quote], quote[:author]) }
end
end
describe ".generate" do
it "returns a bundled quote without contacting any external service" do
- expect(bundled_quotes("en")).to include(described_class.generate(user))
+ expect(bundled_quotes).to include(described_class.generate(user))
end
it "localizes the quote to the user's effective locale" do
SiteSetting.allow_user_locale = true
user.update!(locale: "fr")
- expect(bundled_quotes("fr")).to include(described_class.generate(user))
+ expect(bundled_quotes).to include(described_class.generate(user))
end
end
end
diff --git a/plugins/discourse-narrative-bot/spec/user_spec.rb b/plugins/discourse-narrative-bot/spec/user_spec.rb
index 9f7bbaad26a..6f001f01a38 100644
--- a/plugins/discourse-narrative-bot/spec/user_spec.rb
+++ b/plugins/discourse-narrative-bot/spec/user_spec.rb
@@ -3,14 +3,7 @@
RSpec.describe User do
let(:user) { Fabricate(:user) }
let(:profile_page_url) { "#{Discourse.base_url}/users/#{user.username}" }
-
- def i18n_post_args(extra = {})
- { base_uri: "" }.merge(extra)
- end
-
- def i18n_t(key, params = {})
- I18n.t(key, i18n_post_args.merge(params))
- end
+ let(:i18n_post_args) { { base_uri: "" } }
before do
stub_image_size
@@ -26,8 +19,9 @@ RSpec.describe User do
user
expected_raw =
- i18n_t(
+ I18n.t(
"discourse_narrative_bot.new_user_narrative.hello.message",
+ **i18n_post_args,
username: user.username,
title: SiteSetting.title,
)
@@ -54,10 +48,10 @@ RSpec.describe User do
expect { user }.to change { Topic.count }.by(1)
expect(Topic.last.title).to eq(
- i18n_t("discourse_narrative_bot.new_user_narrative.hello.title").gsub(
- /:robot:/,
- "",
- ).strip,
+ I18n
+ .t("discourse_narrative_bot.new_user_narrative.hello.title", **i18n_post_args)
+ .gsub(/:robot:/, "")
+ .strip,
)
end
end
@@ -69,7 +63,7 @@ RSpec.describe User do
expect { user }.to change { Topic.count }.by(1)
expect(Topic.last.title).to eq(
- i18n_t("discourse_narrative_bot.new_user_narrative.hello.title"),
+ I18n.t("discourse_narrative_bot.new_user_narrative.hello.title", **i18n_post_args),
)
end
@@ -80,7 +74,11 @@ RSpec.describe User do
expect { user }.to change { Topic.count }.by(1)
expect(Topic.last.title).to eq(
- i18n_t("system_messages.welcome_user.subject_template", site_name: SiteSetting.title),
+ I18n.t(
+ "system_messages.welcome_user.subject_template",
+ **i18n_post_args,
+ site_name: SiteSetting.title,
+ ),
)
end
end
diff --git a/plugins/discourse-patreon/spec/integration/patreon_auth_spec.rb b/plugins/discourse-patreon/spec/integration/patreon_auth_spec.rb
index 8be5ddaede7..81e0880bf82 100644
--- a/plugins/discourse-patreon/spec/integration/patreon_auth_spec.rb
+++ b/plugins/discourse-patreon/spec/integration/patreon_auth_spec.rb
@@ -22,7 +22,27 @@ describe "Patreon Oauth2" do
expect(response.status).to eq(302)
expect(response.location).to start_with("https://www.patreon.com/oauth2/authorize")
- setup_patreon_stubs(email: user1.email, verified: false)
+ stub_request(:get, identity_url).with(
+ headers: {
+ "Authorization" => "Bearer #{access_token}",
+ },
+ ).to_return(
+ status: 200,
+ body:
+ JSON.dump(
+ data: {
+ id: "493290423324",
+ attributes: {
+ email: user1.email,
+ full_name: "Patron",
+ is_email_verified: false,
+ },
+ },
+ ),
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
post "/auth/patreon/callback", params: { state: session["omniauth.state"], code: temp_code }
expect(response.status).to eq(302)
@@ -35,7 +55,27 @@ describe "Patreon Oauth2" do
expect(response.status).to eq(302)
expect(response.location).to start_with("https://www.patreon.com/oauth2/authorize")
- setup_patreon_stubs(email: user1.email, verified: true)
+ stub_request(:get, identity_url).with(
+ headers: {
+ "Authorization" => "Bearer #{access_token}",
+ },
+ ).to_return(
+ status: 200,
+ body:
+ JSON.dump(
+ data: {
+ id: "493290423324",
+ attributes: {
+ email: user1.email,
+ full_name: "Patron",
+ is_email_verified: true,
+ },
+ },
+ ),
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
post "/auth/patreon/callback", params: { state: session["omniauth.state"], code: temp_code }
expect(response.status).to eq(302)
@@ -45,6 +85,8 @@ describe "Patreon Oauth2" do
end
context "with API v1" do
+ let(:identity_url) { "https://api.patreon.com/oauth2/api/current_user" }
+
before do
SiteSetting.patreon_api_version = "1"
@@ -66,34 +108,14 @@ describe "Patreon Oauth2" do
)
end
- def setup_patreon_stubs(email:, verified:)
- stub_request(:get, "https://api.patreon.com/oauth2/api/current_user").with(
- headers: {
- "Authorization" => "Bearer #{access_token}",
- },
- ).to_return(
- status: 200,
- body:
- JSON.dump(
- data: {
- id: "493290423324",
- attributes: {
- email: email,
- full_name: "Patron",
- is_email_verified: verified,
- },
- },
- ),
- headers: {
- "Content-Type" => "application/json",
- },
- )
- end
-
include_examples "patreon oauth"
end
context "with API v2" do
+ let(:identity_url) do
+ "https://www.patreon.com/api/oauth2/v2/identity?fields%5Buser%5D=email,full_name,is_email_verified"
+ end
+
before do
SiteSetting.patreon_api_version = "2"
@@ -115,29 +137,6 @@ describe "Patreon Oauth2" do
)
end
- def setup_patreon_stubs(email:, verified:)
- stub_request(
- :get,
- "https://www.patreon.com/api/oauth2/v2/identity?fields%5Buser%5D=email,full_name,is_email_verified",
- ).with(headers: { "Authorization" => "Bearer #{access_token}" }).to_return(
- status: 200,
- body:
- JSON.dump(
- data: {
- id: "493290423324",
- attributes: {
- email: email,
- full_name: "Patron",
- is_email_verified: verified,
- },
- },
- ),
- headers: {
- "Content-Type" => "application/json",
- },
- )
- end
-
include_examples "patreon oauth"
end
end
diff --git a/plugins/discourse-policy/spec/lib/check_policy_spec.rb b/plugins/discourse-policy/spec/lib/check_policy_spec.rb
index 887d824cbf5..df0782efc48 100644
--- a/plugins/discourse-policy/spec/lib/check_policy_spec.rb
+++ b/plugins/discourse-policy/spec/lib/check_policy_spec.rb
@@ -18,10 +18,6 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
Jobs.run_immediately!
end
- def accept_policy(post)
- [user1, user2].each { |u| PolicyUser.add!(u, post.post_policy) }
- end
-
it "correctly renews policies with no renew-start" do
freeze_time Time.utc(2019)
@@ -34,7 +30,7 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post = create_post(raw: raw, user: Fabricate(:admin))
freeze_time Time.utc(2021)
- accept_policy(post)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
freeze_time Time.utc(2022)
job.execute
@@ -61,7 +57,7 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post = create_post(raw: raw, user: Fabricate(:admin))
freeze_time Time.utc(2021)
- accept_policy(post)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
freeze_time Time.utc(2022)
PolicyUser.where(user_id: user2.id).update(accepted_at: Time.now)
@@ -90,8 +86,8 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post2 = create_post(raw: raw2, user: Fabricate(:admin))
freeze_time Time.utc(2021)
- accept_policy(post)
- accept_policy(post2)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post2.post_policy) }
freeze_time Time.utc(2022)
job.execute
@@ -112,7 +108,7 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post = create_post(raw: raw, user: Fabricate(:admin))
- accept_policy(post)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
freeze_time Time.utc(2020)
job.execute
@@ -128,7 +124,7 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post.reload
expect(post.post_policy.accepted_by).to be_empty
- accept_policy(post)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
freeze_time(Time.utc(2020, 10, 17) + 101.days)
@@ -161,7 +157,7 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post = create_post(raw: raw, user: Fabricate(:admin))
- accept_policy(post)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
freeze_time Time.utc(2020, 10, 17)
@@ -201,7 +197,7 @@ describe Jobs::DiscoursePolicy::CheckPolicy do
post = create_post(raw: raw, user: Fabricate(:admin))
- accept_policy(post)
+ [user1, user2].each { |policy_user| PolicyUser.add!(policy_user, post.post_policy) }
freeze_time Time.utc(2020, 10, 30)
diff --git a/plugins/discourse-policy/spec/requests/policy_controller_spec.rb b/plugins/discourse-policy/spec/requests/policy_controller_spec.rb
index 36bcafd0f44..f727db7407f 100644
--- a/plugins/discourse-policy/spec/requests/policy_controller_spec.rb
+++ b/plugins/discourse-policy/spec/requests/policy_controller_spec.rb
@@ -13,13 +13,11 @@ describe DiscoursePolicy::PolicyController do
group.add(user2)
end
- def raw
- <<~MD
+ let(:raw) { <<~MD }
[policy group=#{group.name}]
I always open **doors**!
[/policy]
MD
- end
it "allows users to accept/reject policy" do
post = create_post(raw: raw, user: moderator)
@@ -156,13 +154,11 @@ describe DiscoursePolicy::PolicyController do
describe "private policy restrictions" do
fab!(:admin)
- def private_raw
- <<~MD
+ let(:private_raw) { <<~MD }
[policy group=#{group.name} private=true]
I always open **doors**!
[/policy]
MD
- end
it "denies non-admin access to accepted users for a private policy" do
post = create_post(raw: private_raw, user: moderator)
diff --git a/plugins/discourse-post-voting/spec/lib/email/receiver_spec.rb b/plugins/discourse-post-voting/spec/lib/email/receiver_spec.rb
index 5b0b83d8924..e9cb464b416 100644
--- a/plugins/discourse-post-voting/spec/lib/email/receiver_spec.rb
+++ b/plugins/discourse-post-voting/spec/lib/email/receiver_spec.rb
@@ -9,20 +9,21 @@ RSpec.describe Email::Receiver do
SiteSetting.alternative_reply_by_email_addresses = "alt+%{reply_key}@bar.com"
end
- def process(email_name, opts = {})
- Email::Receiver.new(email(email_name), opts).process!
- end
-
describe "reply" do
- let(:reply_key) { "4f97315cc828096c9cb34c6f1a0d6fe8" }
fab!(:category)
fab!(:user) { Fabricate(:user, email: "[email protected]", refresh_auto_groups: true) }
fab!(:topic) do
create_topic(category: category, user: user, subtype: Topic::POST_VOTING_SUBTYPE)
end
fab!(:post) { create_post(topic: topic) }
-
- before { Fabricate(:post_reply_key, reply_key: reply_key, user: user, post: post) }
+ fab!(:post_reply_key) do
+ Fabricate(
+ :post_reply_key,
+ reply_key: "4f97315cc828096c9cb34c6f1a0d6fe8",
+ user: user,
+ post: post,
+ )
+ end
it "creates a new reply post" do
handler_calls = 0
@@ -30,7 +31,7 @@ RSpec.describe Email::Receiver do
DiscourseEvent.on(:topic_created, &handler)
- expect { process(:html_reply) }.to change { topic.posts.count }
+ expect { described_class.new(email(:html_reply)).process! }.to change { topic.posts.count }
last_post = topic.posts.last
expect(last_post.raw).to eq("This is a **HTML** reply ;)")
expect(last_post.reply_to_post_number).to be_nil
diff --git a/plugins/discourse-post-voting/spec/lib/topic_view_spec.rb b/plugins/discourse-post-voting/spec/lib/topic_view_spec.rb
index dd317d5f70f..8aa0a84ad5c 100644
--- a/plugins/discourse-post-voting/spec/lib/topic_view_spec.rb
+++ b/plugins/discourse-post-voting/spec/lib/topic_view_spec.rb
@@ -140,17 +140,13 @@ describe TopicView do
end
end
- def topic_view_near(post)
- TopicView.new(topic.id, user, post_number: post.post_number)
- end
-
before do
Topic.reset_highest(topic.id)
TopicView.stubs(:chunk_size).returns(3)
end
it "snaps to the lower boundary" do
- near_view = topic_view_near(post)
+ near_view = TopicView.new(topic.id, user, post_number: post.post_number)
expect(near_view.desired_post.id).to eq(post.id)
expect(near_view.posts.map(&:id)).to eq(
[post.id, answer_plus_2_votes.id, answer_plus_1_vote.id],
@@ -158,7 +154,7 @@ describe TopicView do
end
it "snaps to the upper boundary" do
- near_view = topic_view_near(answer_minus_2_votes)
+ near_view = TopicView.new(topic.id, user, post_number: answer_minus_2_votes.post_number)
expect(near_view.desired_post.id).to eq(answer_minus_2_votes.id)
expect(near_view.posts.map(&:id)).to eq(
@@ -167,7 +163,7 @@ describe TopicView do
end
it "returns the posts in the middle" do
- near_view = topic_view_near(answer_0_votes)
+ near_view = TopicView.new(topic.id, user, post_number: answer_0_votes.post_number)
expect(near_view.desired_post.id).to eq(answer_0_votes.id)
expect(near_view.posts.map(&:id)).to eq(
[answer_plus_1_vote.id, answer_0_votes.id, answer_minus_1_vote.id],
diff --git a/plugins/discourse-reactions/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-reactions/spec/serializers/topic_view_serializer_spec.rb
index 3b64ff9c601..4034a759bc2 100644
--- a/plugins/discourse-reactions/spec/serializers/topic_view_serializer_spec.rb
+++ b/plugins/discourse-reactions/spec/serializers/topic_view_serializer_spec.rb
@@ -99,6 +99,10 @@ describe TopicViewSerializer do
fab!(:reaction_user_heart_ignored) do
Fabricate(:reaction_user, reaction: heart, user: another_ignored)
end
+ fab!(:ignored_user_record) { Fabricate(:ignored_user, user: viewer, ignored_user: ignored) }
+ fab!(:another_ignored_user_record) do
+ Fabricate(:ignored_user, user: viewer, ignored_user: another_ignored)
+ end
fab!(:like_other_post_2) do
Fabricate(
:post_action,
@@ -117,34 +121,27 @@ describe TopicViewSerializer do
end
let(:topic) { post_1.topic }
+ let(:serialized_topic_view) do
+ described_class.new(
+ TopicView.new(topic, viewer),
+ scope: Guardian.new(viewer),
+ root: false,
+ ).as_json
+ end
before do
SiteSetting.discourse_reactions_like_icon = "heart"
SiteSetting.discourse_reactions_enabled_reactions = "otter|heart"
- Fabricate(:ignored_user, user: viewer, ignored_user: ignored)
- Fabricate(:ignored_user, user: viewer, ignored_user: another_ignored)
- end
-
- def serialize_for(user)
- TopicViewSerializer.new(
- TopicView.new(topic, user),
- scope: Guardian.new(user),
- root: false,
- ).as_json
end
it "excludes ignored users from preloaded :reactions" do
- json = serialize_for(viewer)
-
- posts = json[:post_stream][:posts]
+ posts = serialized_topic_view[:post_stream][:posts]
expect(posts[0][:reactions]).to contain_exactly({ id: "otter", type: :emoji, count: 1 })
expect(posts[1][:reactions]).to contain_exactly({ id: "heart", type: :emoji, count: 1 })
end
it "excludes ignored users from preloaded :reaction_users_count" do
- json = serialize_for(viewer)
-
- posts = json[:post_stream][:posts]
+ posts = serialized_topic_view[:post_stream][:posts]
expect(posts[0][:reaction_users_count]).to eq(1)
expect(posts[1][:reaction_users_count]).to eq(1)
end
@@ -162,7 +159,12 @@ describe TopicViewSerializer do
end
it "still shows global counts for viewers with no ignored users" do
- json = serialize_for(other_user)
+ json =
+ described_class.new(
+ TopicView.new(topic, other_user),
+ scope: Guardian.new(other_user),
+ root: false,
+ ).as_json
posts = json[:post_stream][:posts]
expect(posts[0][:reactions]).to contain_exactly(
diff --git a/plugins/discourse-reactions/spec/services/reaction_manager_spec.rb b/plugins/discourse-reactions/spec/services/reaction_manager_spec.rb
index 849030f0285..fded1206122 100644
--- a/plugins/discourse-reactions/spec/services/reaction_manager_spec.rb
+++ b/plugins/discourse-reactions/spec/services/reaction_manager_spec.rb
@@ -1,10 +1,12 @@
# frozen_string_literal: true
RSpec.describe DiscourseReactions::ReactionManager do
- def reaction_manager(reaction_value)
+ subject(:reaction_manager) do
described_class.new(reaction_value: reaction_value, user: user, post: post)
end
+ let(:reaction_value) { "-1" }
+
fab!(:user)
fab!(:post)
fab!(:reaction_plus_one) { Fabricate(:reaction, reaction_value: "+1", post: post) }
@@ -16,10 +18,12 @@ RSpec.describe DiscourseReactions::ReactionManager do
describe ".toggle!" do
context "when user is silenced" do
+ let(:reaction_value) { "clap" }
+
before { user.update!(silenced_till: 1.year.from_now) }
it "raises InvalidAccess when trying to toggle reaction" do
- expect { reaction_manager("clap").toggle! }.to raise_error(Discourse::InvalidAccess)
+ expect { reaction_manager.toggle! }.to raise_error(Discourse::InvalidAccess)
end
end
@@ -55,41 +59,43 @@ RSpec.describe DiscourseReactions::ReactionManager do
context "when the user has not yet reacted to the post" do
context "when the new reaction matches discourse_reactions_reaction_for_like" do
+ let(:reaction_value) { "clap" }
+
it "does create a PostAction record" do
- expect { reaction_manager("clap").toggle! }.to change { PostAction.count }.by(1)
+ expect { reaction_manager.toggle! }.to change { PostAction.count }.by(1)
end
it "does not create a ReactionUser record" do
- expect { reaction_manager("clap").toggle! }.not_to change {
+ expect { reaction_manager.toggle! }.not_to change {
DiscourseReactions::ReactionUser.count
}
end
it "creates a reaction notification" do
- expect { reaction_manager("clap").toggle! }.to change { Notification.count }.by(1)
+ expect { reaction_manager.toggle! }.to change { Notification.count }.by(1)
end
end
context "when the new reaction does not match discourse_reactions_reaction_for_like" do
+ let(:reaction_value) { "+1" }
+
it "does create a PostAction record" do
- expect { reaction_manager("+1").toggle! }.to change { PostAction.count }
+ expect { reaction_manager.toggle! }.to change { PostAction.count }
end
it "does create a ReactionUser record" do
- expect { reaction_manager("+1").toggle! }.to change {
- DiscourseReactions::ReactionUser.count
- }
+ expect { reaction_manager.toggle! }.to change { DiscourseReactions::ReactionUser.count }
end
it "creates a reaction notification" do
- expect { reaction_manager("+1").toggle! }.to change { Notification.count }.by(1)
+ expect { reaction_manager.toggle! }.to change { Notification.count }.by(1)
end
context "when the reaction is in discourse_reactions_excluded_from_like" do
before { SiteSetting.discourse_reactions_excluded_from_like = "+1" }
it "does not create a PostAction record" do
- expect { reaction_manager("+1").toggle! }.not_to change { PostAction.count }
+ expect { reaction_manager.toggle! }.not_to change { PostAction.count }
end
end
end
@@ -103,16 +109,16 @@ RSpec.describe DiscourseReactions::ReactionManager do
context "when the user has permission to delete the ReactionUser" do
it "removes the ReactionUser for the old +1 reaction" do
- reaction_manager("-1").toggle!
+ reaction_manager.toggle!
expect(DiscourseReactions::ReactionUser.find_by(id: reaction_user.id)).to be_nil
end
it "removes any PostAction that exists as well" do
- expect { reaction_manager("-1").toggle! }.to change { PostAction.count }.by(-1)
+ expect { reaction_manager.toggle! }.to change { PostAction.count }.by(-1)
end
it "adds a new ReactionUser record for the new reaction -1 but not PostAction because of discourse_reactions_excluded_from_like" do
- reaction_manager("-1").toggle!
+ reaction_manager.toggle!
expect(
DiscourseReactions::ReactionUser.find_by(
reaction: reaction_minus_one,
@@ -130,7 +136,7 @@ RSpec.describe DiscourseReactions::ReactionManager do
end
it "adds a new ReactionUser record and a PostAction record for reaction hugs" do
- reaction_manager("hugs").toggle!
+ described_class.new(reaction_value: "hugs", user: user, post: post).toggle!
expect(
DiscourseReactions::ReactionUser.find_by(
reaction: reaction_hugs,
@@ -149,7 +155,7 @@ RSpec.describe DiscourseReactions::ReactionManager do
it "deletes any notifications for the old Reaction and creates a notification for the new reaction" do
DiscourseReactions::ReactionNotification.new(reaction_plus_one, user).create
- expect { reaction_manager("-1").toggle! }.not_to change { Notification.count }
+ expect { reaction_manager.toggle! }.not_to change { Notification.count }
expect(
Notification.where(
notification_type: Notification.types[:reaction],
@@ -161,7 +167,7 @@ RSpec.describe DiscourseReactions::ReactionManager do
end
it "removes the Reaction record attached to the post when no more users have reacted to it" do
- expect { reaction_manager("-1").toggle! }.to change {
+ expect { reaction_manager.toggle! }.to change {
DiscourseReactions::Reaction.where(id: reaction_plus_one).count
}.by(-1)
end
@@ -170,7 +176,7 @@ RSpec.describe DiscourseReactions::ReactionManager do
before { reaction_user.update!(reaction: reaction_minus_one) }
it "does not add a new ReactionUser record, just removes the old one" do
- expect { reaction_manager("-1").toggle! }.to change {
+ expect { reaction_manager.toggle! }.to change {
DiscourseReactions::ReactionUser.count
}.by(-1).and change { PostAction.count }.by(-1)
end
@@ -185,7 +191,7 @@ RSpec.describe DiscourseReactions::ReactionManager do
end
it "raises an error" do
- expect { reaction_manager("-1").toggle! }.to raise_error(Discourse::InvalidAccess)
+ expect { reaction_manager.toggle! }.to raise_error(Discourse::InvalidAccess)
end
end
end
@@ -202,18 +208,18 @@ RSpec.describe DiscourseReactions::ReactionManager do
context "when the user has permission to delete the PostAction" do
it "removes the PostAction" do
- expect { reaction_manager("-1").toggle! }.to change { PostAction.count }.by(-1)
+ expect { reaction_manager.toggle! }.to change { PostAction.count }.by(-1)
end
it "removes the Reaction record attached to the post" do
- expect { reaction_manager("-1").toggle! }.to change {
+ expect { reaction_manager.toggle! }.to change {
DiscourseReactions::Reaction.where(id: reaction_clap).count
}.by(-1)
end
it "deletes any notifications for the old Reaction and creates a notification for the new reaction" do
DiscourseReactions::ReactionNotification.new(reaction_clap, user).create
- expect { reaction_manager("-1").toggle! }.not_to change { Notification.count }
+ expect { reaction_manager.toggle! }.not_to change { Notification.count }
expect(
Notification.where(
notification_type: Notification.types[:reaction],
@@ -233,7 +239,7 @@ RSpec.describe DiscourseReactions::ReactionManager do
end
it "raises an error" do
- expect { reaction_manager("-1").toggle! }.to raise_error(Discourse::InvalidAccess)
+ expect { reaction_manager.toggle! }.to raise_error(Discourse::InvalidAccess)
end
end
end
diff --git a/plugins/discourse-rewind/spec/actions/reading_time_spec.rb b/plugins/discourse-rewind/spec/actions/reading_time_spec.rb
index 4f4130bbfde..cbb66b7aedd 100644
--- a/plugins/discourse-rewind/spec/actions/reading_time_spec.rb
+++ b/plugins/discourse-rewind/spec/actions/reading_time_spec.rb
@@ -30,10 +30,6 @@ RSpec.describe DiscourseRewind::Action::ReadingTime do
)
end
- def new_target_time_read(value)
- value - 1000
- end
-
it "calculates reading time for the year correctly" do
result = call_report
expect(result[:data][:reading_time]).to eq(1100)
@@ -43,103 +39,103 @@ RSpec.describe DiscourseRewind::Action::ReadingTime do
result = call_report
expect(result[:data][:book]).to eq("The Metamorphosis")
- user_visit_1.update!(time_read: new_target_time_read(5300))
+ user_visit_1.update!(time_read: 5300 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Little Prince")
- user_visit_1.update!(time_read: new_target_time_read(7100))
+ user_visit_1.update!(time_read: 7100 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Animal Farm")
- user_visit_1.update!(time_read: new_target_time_read(10_700))
+ user_visit_1.update!(time_read: 10_700 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Alchemist")
- user_visit_1.update!(time_read: new_target_time_read(12_500))
+ user_visit_1.update!(time_read: 12_500 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Great Gatsby")
- user_visit_1.update!(time_read: new_target_time_read(14_900))
+ user_visit_1.update!(time_read: 14_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Fahrenheit 451")
- user_visit_1.update!(time_read: new_target_time_read(16_100))
+ user_visit_1.update!(time_read: 16_100 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("And Then There Were None")
- user_visit_1.update!(time_read: new_target_time_read(16_700))
+ user_visit_1.update!(time_read: 16_700 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("1984")
- user_visit_1.update!(time_read: new_target_time_read(17_900))
+ user_visit_1.update!(time_read: 17_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Catcher in the Rye")
- user_visit_1.update!(time_read: new_target_time_read(19_640))
+ user_visit_1.update!(time_read: 19_640 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Hunger Games")
- user_visit_1.update!(time_read: new_target_time_read(22_700))
+ user_visit_1.update!(time_read: 22_700 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("To Kill a Mockingbird")
- user_visit_1.update!(time_read: new_target_time_read(24_500))
+ user_visit_1.update!(time_read: 24_500 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("A Tale of Two Cities")
- user_visit_1.update!(time_read: new_target_time_read(25_100))
+ user_visit_1.update!(time_read: 25_100 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Pride and Prejudice")
- user_visit_1.update!(time_read: new_target_time_read(26_900))
+ user_visit_1.update!(time_read: 26_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Hobbit")
- user_visit_1.update!(time_read: new_target_time_read(29_900))
+ user_visit_1.update!(time_read: 29_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Little Women")
- user_visit_1.update!(time_read: new_target_time_read(34_100))
+ user_visit_1.update!(time_read: 34_100 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Jane Eyre")
- user_visit_1.update!(time_read: new_target_time_read(37_700))
+ user_visit_1.update!(time_read: 37_700 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Da Vinci Code")
- user_visit_1.update!(time_read: new_target_time_read(46_700))
+ user_visit_1.update!(time_read: 46_700 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("One Hundred Years of Solitude")
- user_visit_1.update!(time_read: new_target_time_read(107_900))
+ user_visit_1.update!(time_read: 107_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Lord of the Rings")
- user_visit_1.update!(time_read: new_target_time_read(179_900))
+ user_visit_1.update!(time_read: 179_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Complete works of Shakespeare")
- user_visit_1.update!(time_read: new_target_time_read(359_900))
+ user_visit_1.update!(time_read: 359_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Game of Thrones Series")
- user_visit_1.update!(time_read: new_target_time_read(719_900))
+ user_visit_1.update!(time_read: 719_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Malazan Book of the Fallen")
- user_visit_1.update!(time_read: new_target_time_read(1_439_900))
+ user_visit_1.update!(time_read: 1_439_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("Terry Pratchett's Discworld series")
- user_visit_1.update!(time_read: new_target_time_read(2_159_900))
+ user_visit_1.update!(time_read: 2_159_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Wandering Inn web series")
- user_visit_1.update!(time_read: new_target_time_read(2_879_900))
+ user_visit_1.update!(time_read: 2_879_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Combined Cosmere works + Wheel of Time")
- user_visit_1.update!(time_read: new_target_time_read(3_599_900))
+ user_visit_1.update!(time_read: 3_599_900 - user_visit_2.time_read)
result = call_report
expect(result[:data][:book]).to eq("The Star Trek novels")
end
diff --git a/plugins/discourse-rewind/spec/serializers/user_option_serializer_spec.rb b/plugins/discourse-rewind/spec/serializers/user_option_serializer_spec.rb
index 95cb4b00168..91abac3b356 100644
--- a/plugins/discourse-rewind/spec/serializers/user_option_serializer_spec.rb
+++ b/plugins/discourse-rewind/spec/serializers/user_option_serializer_spec.rb
@@ -9,10 +9,6 @@ RSpec.describe UserOptionSerializer do
UserOptionSerializer.new(user.user_option, scope: Guardian.new(user), root: false)
end
- def set_dismissed_at(date_string)
- user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse(date_string))
- end
-
describe "#discourse_rewind_dismissed" do
it "returns false when dismissed_at is nil" do
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(false)
@@ -22,17 +18,17 @@ RSpec.describe UserOptionSerializer do
before { freeze_time DateTime.parse("2024-12-15") }
it "returns true when dismissed in Dec 2024" do
- set_dismissed_at("2024-12-01")
+ user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse("2024-12-01"))
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(true)
end
it "returns false when dismissed in Jan 2024 (was for rewind 2023)" do
- set_dismissed_at("2024-01-10")
+ user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse("2024-01-10"))
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(false)
end
it "returns false when dismissed in Dec 2023" do
- set_dismissed_at("2023-12-01")
+ user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse("2023-12-01"))
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(false)
end
end
@@ -41,17 +37,17 @@ RSpec.describe UserOptionSerializer do
before { freeze_time DateTime.parse("2025-01-15") }
it "returns true when dismissed in Dec 2024" do
- set_dismissed_at("2024-12-20")
+ user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse("2024-12-20"))
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(true)
end
it "returns true when dismissed in Jan 2025" do
- set_dismissed_at("2025-01-05")
+ user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse("2025-01-05"))
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(true)
end
it "returns false when dismissed in Jan 2024 (was for rewind 2023)" do
- set_dismissed_at("2024-01-20")
+ user.user_option.update!(discourse_rewind_dismissed_at: DateTime.parse("2024-01-20"))
expect(serializer.as_json[:discourse_rewind_dismissed]).to eq(false)
end
end
diff --git a/plugins/discourse-rss-polling/spec/services/rss_feed/action/build_preview_spec.rb b/plugins/discourse-rss-polling/spec/services/rss_feed/action/build_preview_spec.rb
index 8daf2b43277..63f1f4a6b45 100644
--- a/plugins/discourse-rss-polling/spec/services/rss_feed/action/build_preview_spec.rb
+++ b/plugins/discourse-rss-polling/spec/services/rss_feed/action/build_preview_spec.rb
@@ -4,10 +4,17 @@ RSpec.describe DiscourseRssPolling::RssFeed::Action::BuildPreview do
subject(:preview) { described_class.call(feed_items:, feed_category_filter:) }
let(:feed_category_filter) { nil }
+ let(:title) { "Hello" }
+ let(:content) { "Body" }
+ let(:categories) { [] }
+ let(:url) { "https://example.com/post" }
+ let(:feed_item) do
+ instance_double(DiscourseRssPolling::FeedItem, title:, content:, categories:, url:)
+ end
+ let(:feed_items) { [feed_item] }
- def feed_item(title:, content:, categories: [], url: "https://example.com/post")
- item = instance_double(DiscourseRssPolling::FeedItem, title:, content:, categories:, url:)
- allow(item).to receive(:outcome) do |status:, reason: nil, topic_url: nil|
+ before do
+ allow(feed_item).to receive(:outcome) do |status:, reason: nil, topic_url: nil|
{
"title" => title,
"status" => status.to_s,
@@ -15,19 +22,16 @@ RSpec.describe DiscourseRssPolling::RssFeed::Action::BuildPreview do
"topic_url" => topic_url,
}
end
- item
end
context "when an item would be imported" do
- let(:feed_items) { [feed_item(title: "Hello", content: "Body")] }
-
it "marks the item as would_import" do
expect(preview.first).to include("status" => "would_import", "topic_url" => nil)
end
end
context "when an item is skipped" do
- let(:feed_items) { [feed_item(title: nil, content: "Body")] }
+ let(:title) { nil }
it "marks the item as skipped with a reason" do
expect(preview.first).to include("status" => "skipped", "reason" => "missing_title")
@@ -36,8 +40,7 @@ RSpec.describe DiscourseRssPolling::RssFeed::Action::BuildPreview do
context "when an item has already been imported" do
let(:imported_url) { "https://blog.discourse.org/2017/09/poll-feed-spec-fixture/" }
-
- let(:feed_items) { [feed_item(title: "Hello", content: "Body", url: imported_url)] }
+ let(:url) { imported_url }
before do
TopicEmbed.import(Discourse.system_user, imported_url, "Poll Feed Spec Fixture", "content")
diff --git a/plugins/discourse-solved/spec/integration/admin_dashboard_highlight_kpi_spec.rb b/plugins/discourse-solved/spec/integration/admin_dashboard_highlight_kpi_spec.rb
index 23863b89655..231a9998fab 100644
--- a/plugins/discourse-solved/spec/integration/admin_dashboard_highlight_kpi_spec.rb
+++ b/plugins/discourse-solved/spec/integration/admin_dashboard_highlight_kpi_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
describe "discourse-solved admin dashboard highlight KPI" do
- def lookup_kpi
+ let(:accepted_solutions_kpi) do
DiscoursePluginRegistry.admin_dashboard_highlight_kpis.find do |kpi|
kpi[:type] == :accepted_solutions
end
@@ -15,19 +15,19 @@ describe "discourse-solved admin dashboard highlight KPI" do
after { Discourse.cache.clear }
it "is registered with the plugin registry" do
- expect(lookup_kpi).to be_present
- expect(lookup_kpi[:report]).to eq("accepted_solutions")
+ expect(accepted_solutions_kpi).to be_present
+ expect(accepted_solutions_kpi[:report]).to eq("accepted_solutions")
end
describe "enabled lambda" do
it "returns false when no category opts in and the global setting is off" do
- expect(lookup_kpi[:enabled].call).to eq(false)
+ expect(accepted_solutions_kpi[:enabled].call).to eq(false)
end
it "returns true when allow_solved_on_all_topics is enabled" do
SiteSetting.allow_solved_on_all_topics = true
- expect(lookup_kpi[:enabled].call).to eq(true)
+ expect(accepted_solutions_kpi[:enabled].call).to eq(true)
end
it "returns true when at least one category opts in via custom field" do
@@ -38,7 +38,7 @@ describe "discourse-solved admin dashboard highlight KPI" do
value: "true",
)
- expect(lookup_kpi[:enabled].call).to eq(true)
+ expect(accepted_solutions_kpi[:enabled].call).to eq(true)
end
end
end
diff --git a/plugins/discourse-solved/spec/integration/enable_solved_badges_spec.rb b/plugins/discourse-solved/spec/integration/enable_solved_badges_spec.rb
index aedfdb1fe4a..d3b086fef58 100644
--- a/plugins/discourse-solved/spec/integration/enable_solved_badges_spec.rb
+++ b/plugins/discourse-solved/spec/integration/enable_solved_badges_spec.rb
@@ -3,14 +3,10 @@
RSpec.describe "Enable Solved badges by default upcoming change" do
let(:badge_names) { ["Solved 1", "Solved 2", "Solved 3", "Solved 4"] }
- def reseed_solved_badges
- Badge.where(name: badge_names).delete_all
- load Rails.root.join("plugins/discourse-solved/db/fixtures/001_badges.rb") # rubocop:disable Discourse/Plugins/UseRequireRelative
- end
-
describe "seeding the Solved badges on a new site" do
it "enables the badges by default" do
- reseed_solved_badges
+ Badge.where(name: badge_names).delete_all
+ load Rails.root.join("plugins/discourse-solved/db/fixtures/001_badges.rb") # rubocop:disable Discourse/Plugins/UseRequireRelative
expect(Badge.where(name: badge_names).pluck(:enabled)).to all(eq(true))
end
diff --git a/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb b/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
index 8f67c7a2a3e..97bbf49d301 100644
--- a/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
+++ b/plugins/discourse-solved/spec/lib/discourse_solved/admin_dashboard_support_spec.rb
@@ -7,35 +7,46 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
fab!(:staff_user, :moderator)
fab!(:member_user) { Fabricate(:user, trust_level: TrustLevel[2]) }
+ subject(:dashboard) { described_class.build(**dashboard_options) }
+
before { SiteSetting.solved_enabled = true }
- def build(**opts)
- described_class.build(
- start_date: 30.days.ago.to_s,
- end_date: Time.zone.now.to_s,
- current_user: admin,
- **opts,
- )
+ let(:dashboard_options) do
+ { start_date: 30.days.ago.to_s, end_date: Time.zone.now.to_s, current_user: admin }
+ end
+
+ let(:solved_topic) do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic:, user: author)
+ answer = Fabricate(:post, topic:, user: staff_user)
+ Fabricate(:solved_topic, topic:, answer_post: answer)
+ topic
+ end
+
+ let(:another_solved_topic) do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic:, user: author)
+ answer = Fabricate(:post, topic:, user: staff_user)
+ Fabricate(:solved_topic, topic:, answer_post: answer)
+ topic
end
- def solved_topic(category: support_category, answerer: staff_user)
- topic = Fabricate(:topic, category: category, user: author)
- Fabricate(:post, topic: topic, user: author)
- answer = Fabricate(:post, topic: topic, user: answerer)
- Fabricate(:solved_topic, topic: topic, answer_post: answer)
+ let(:answered_topic) do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic:, user: author)
+ Fabricate(:post, topic:, user: member_user)
topic
end
- def answered_topic(category: support_category, answerer: member_user)
- topic = Fabricate(:topic, category: category, user: author)
- Fabricate(:post, topic: topic, user: author)
- Fabricate(:post, topic: topic, user: answerer)
+ let(:unanswered_topic) do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic:, user: author)
topic
end
- def unanswered_topic(category: support_category)
- topic = Fabricate(:topic, category: category, user: author)
- Fabricate(:post, topic: topic, user: author)
+ let(:another_unanswered_topic) do
+ topic = Fabricate(:topic, category: support_category, user: author)
+ Fabricate(:post, topic:, user: author)
topic
end
@@ -66,7 +77,7 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
answered_topic
unanswered_topic
- expect(build[:topic_outcomes]).to eq(resolved: 1, in_progress: 1, unanswered: 1)
+ expect(dashboard[:topic_outcomes]).to eq(resolved: 1, in_progress: 1, unanswered: 1)
end
it "treats a topic where only the author replied as unanswered, not in progress" do
@@ -74,17 +85,19 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
Fabricate(:post, topic: topic, user: author)
Fabricate(:post, topic: topic, user: author)
- expect(build[:topic_outcomes]).to eq(resolved: 0, in_progress: 0, unanswered: 1)
+ expect(dashboard[:topic_outcomes]).to eq(resolved: 0, in_progress: 0, unanswered: 1)
end
it "serves cached data for the same scope and window within the TTL" do
solved_topic
- expect(build[:topic_outcomes]).to eq(resolved: 1, in_progress: 0, unanswered: 0)
+ first_result = described_class.build(**dashboard_options)
+ expect(first_result[:topic_outcomes]).to eq(resolved: 1, in_progress: 0, unanswered: 0)
- solved_topic
+ another_solved_topic
- expect(build[:topic_outcomes]).to eq(resolved: 1, in_progress: 0, unanswered: 0)
+ cached_result = described_class.build(**dashboard_options)
+ expect(cached_result[:topic_outcomes]).to eq(resolved: 1, in_progress: 0, unanswered: 0)
end
end
@@ -92,9 +105,9 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
it "chooses the key from the absolute resolution rate, not the trend" do
solved_topic
unanswered_topic
- unanswered_topic
+ another_unanswered_topic
- expect(build[:headline][:key]).to eq("struggling")
+ expect(dashboard[:headline][:key]).to eq("struggling")
end
it "reports the resolution direction against the previous period, independent of the level" do
@@ -104,23 +117,23 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
solved_topic
unanswered_topic
- unanswered_topic
+ another_unanswered_topic
- headline = build[:headline]
+ headline = dashboard[:headline]
expect(headline[:key]).to eq("struggling")
expect(headline[:resolution_direction]).to eq("up")
end
it "focuses the answerers clause on staff when staff dominate replies" do
- solved_topic(answerer: staff_user)
+ solved_topic
- expect(build[:headline][:answerers_focus]).to eq("staff")
+ expect(dashboard[:headline][:answerers_focus]).to eq("staff")
end
it "focuses the answerers clause on members when non-staff dominate replies" do
- answered_topic(answerer: member_user)
+ answered_topic
- expect(build[:headline][:answerers_focus]).to eq("members")
+ expect(dashboard[:headline][:answerers_focus]).to eq("members")
end
end
@@ -130,13 +143,18 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
answered_topic
unanswered_topic
- expect(build[:kpis][:resolution_rate][:value]).to eq(33.3)
+ expect(dashboard[:kpis][:resolution_rate][:value]).to eq(33.3)
end
it "carries the selected categories into the report drill-down query" do
solved_topic
- query = build(category_ids: [support_category.id])[:kpis][:resolution_rate][:report_query]
+ query =
+ described_class.build(**dashboard_options, category_ids: [support_category.id])[:kpis][
+ :resolution_rate
+ ][
+ :report_query
+ ]
expect(query[:filters]).to eq(category_ids: support_category.id.to_s)
end
@@ -144,14 +162,14 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
it "omits the category filter when viewing all categories" do
solved_topic
- expect(build[:kpis][:resolution_rate][:report_query]).not_to have_key(:filters)
+ expect(dashboard[:kpis][:resolution_rate][:report_query]).not_to have_key(:filters)
end
it "reports a nil previous value when the previous period had no topics" do
solved_topic
answered_topic
- kpis = build[:kpis]
+ kpis = dashboard[:kpis]
expect(kpis[:resolution_rate][:value]).to eq(50.0)
expect(kpis[:resolution_rate][:previous_value]).to be_nil
expect(kpis[:staff_involvement][:previous_value]).to be_nil
@@ -160,21 +178,21 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
describe "staff involvement KPI" do
it "is the share of topics whose first reply came from staff" do
- solved_topic(answerer: staff_user)
- answered_topic(answerer: member_user)
+ solved_topic
+ answered_topic
- expect(build[:kpis][:staff_involvement][:value]).to eq(50.0)
+ expect(dashboard[:kpis][:staff_involvement][:value]).to eq(50.0)
end
end
describe "who's answering" do
it "groups repliers by staff and trust level, sharing out the totals" do
- solved_topic(answerer: staff_user)
- answered_topic(answerer: member_user)
+ solved_topic
+ answered_topic
- rows = build[:whos_answering][:rows]
+ rows = dashboard[:whos_answering][:rows]
- expect(build[:whos_answering][:total]).to eq(2)
+ expect(dashboard[:whos_answering][:total]).to eq(2)
expect(rows.find { |row| row[:type] == "staff" }[:count]).to eq(1)
expect(rows.find { |row| row[:type] == "member" }[:count]).to eq(1)
end
@@ -184,7 +202,7 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
Fabricate(:post, topic: topic, user: author)
Fabricate(:post, topic: topic, user: author)
- expect(build[:whos_answering][:total]).to eq(0)
+ expect(dashboard[:whos_answering][:total]).to eq(0)
end
end
@@ -192,44 +210,62 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
it "buckets first-reply times and reports the average" do
answered_topic
- distribution = build[:response_time_distribution]
+ distribution = dashboard[:response_time_distribution]
expect(distribution[:buckets].sum { |bucket| bucket[:count] }).to eq(1)
- expect(build[:kpis][:avg_first_reply][:value]).not_to be_nil
+ expect(dashboard[:kpis][:avg_first_reply][:value]).not_to be_nil
end
end
describe "category scoping" do
fab!(:second_support_category, :support_category)
+ let(:second_category_solved_topic) do
+ topic = Fabricate(:topic, category: second_support_category, user: author)
+ Fabricate(:post, topic:, user: author)
+ answer = Fabricate(:post, topic:, user: staff_user)
+ Fabricate(:solved_topic, topic:, answer_post: answer)
+ topic
+ end
+
it "limits metrics to a single category when one is selected" do
- solved_topic(category: support_category)
- solved_topic(category: second_support_category)
+ solved_topic
+ second_category_solved_topic
- expect(build[:topic_outcomes][:resolved]).to eq(2)
- expect(build(category_ids: [support_category.id])[:topic_outcomes][:resolved]).to eq(1)
+ expect(dashboard[:topic_outcomes][:resolved]).to eq(2)
+ scoped_dashboard =
+ described_class.build(**dashboard_options, category_ids: [support_category.id])
+ expect(scoped_dashboard[:topic_outcomes][:resolved]).to eq(1)
end
it "limits metrics to the union of multiple selected categories" do
- solved_topic(category: support_category)
- solved_topic(category: second_support_category)
+ solved_topic
+ second_category_solved_topic
- result = build(category_ids: [support_category.id, second_support_category.id])
+ result =
+ described_class.build(
+ **dashboard_options,
+ category_ids: [support_category.id, second_support_category.id],
+ )
expect(result[:topic_outcomes][:resolved]).to eq(2)
end
it "strips ids that don't correspond to a support category" do
- solved_topic(category: support_category)
+ solved_topic
other_category = Fabricate(:category)
- result = build(category_ids: [support_category.id, other_category.id])
+ result =
+ described_class.build(
+ **dashboard_options,
+ category_ids: [support_category.id, other_category.id],
+ )
expect(result[:category_ids]).to contain_exactly(support_category.id)
end
it "lists both support categories as filter options" do
- expect(build[:category_options].map { |option| option[:id] }).to contain_exactly(
+ expect(dashboard[:category_options].map { |option| option[:id] }).to contain_exactly(
support_category.id,
second_support_category.id,
)
@@ -242,7 +278,7 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
before { SiteSetting.allow_solved_on_all_topics = true }
it "offers every visible category as a filter option, not just flagged ones" do
- ids = build[:category_options].map { |option| option[:id] }
+ ids = dashboard[:category_options].map { |option| option[:id] }
expect(ids).to include(support_category.id, plain_category.id)
end
@@ -253,16 +289,23 @@ RSpec.describe DiscourseSolved::AdminDashboardSupport do
fab!(:restricted_category) { Fabricate(:private_category, group: group) }
fab!(:outsider, :moderator)
+ let!(:restricted_solved_topic) do
+ topic = Fabricate(:topic, category: restricted_category, user: author)
+ Fabricate(:post, topic:, user: author)
+ answer = Fabricate(:post, topic:, user: staff_user)
+ Fabricate(:solved_topic, topic:, answer_post: answer)
+ topic
+ end
+
before do
restricted_category.custom_fields[
DiscourseSolved::ENABLE_ACCEPTED_ANSWERS_CUSTOM_FIELD
] = "true"
restricted_category.save!
- solved_topic(category: restricted_category)
end
it "excludes categories the viewer cannot see" do
- as_admin = build[:topic_outcomes][:resolved]
+ as_admin = dashboard[:topic_outcomes][:resolved]
as_outsider =
described_class.build(
start_date: 30.days.ago.to_s,
diff --git a/plugins/discourse-solved/spec/requests/topics_controller_spec.rb b/plugins/discourse-solved/spec/requests/topics_controller_spec.rb
index f8a3129c970..e3de6b186b9 100644
--- a/plugins/discourse-solved/spec/requests/topics_controller_spec.rb
+++ b/plugins/discourse-solved/spec/requests/topics_controller_spec.rb
@@ -4,8 +4,11 @@ RSpec.describe TopicsController do
let(:p1) { Fabricate(:post, like_count: 1) }
let(:topic) { p1.topic }
let(:p2) { Fabricate(:post, like_count: 2, topic:, user: Fabricate(:user)) }
+ let(:p2_single_answer_json) do
+ ',"acceptedAnswer":[%{answer_json}]' % { answer_json: solved_answer_json(post: p2) }
+ end
- def answer_json(post)
+ def solved_answer_json(post:)
'{"@type":"Answer","author":{"@type":"Person","name":"%{username2}","url":"%{user2_url}"},"dateModified":"%{answer_modified}","datePublished":"%{answered_at}","text":"%{answer_text}","upvoteCount":%{answer_likes},"url":"%{answer_url}"}' %
{
answer_text: post.excerpt,
@@ -18,23 +21,18 @@ RSpec.describe TopicsController do
}
end
- def p2_single_answer_json
- ',"acceptedAnswer":[%{answer_json}]' % { answer_json: answer_json(p2) }
- end
-
- def expected_schema_json(answer_json, answer_count = 1)
+ def solved_schema_json(topic:, first_post:, answers_json:, answer_count: 1)
'<script type="application/ld+json">{"@context":"http://schema.org","@type":"QAPage","name":"%{title}","datePublished":"%{created_at}","mainEntity":{"@type":"Question","answerCount":%{answer_count},"author":{"@type":"Person","name":"%{username1}","url":"%{user1_url}"},"dateModified":"%{question_modified}","datePublished":"%{created_at}","name":"%{title}","text":"%{question_text}","upvoteCount":%{question_likes}%{answer_json}}}</script>' %
- # rubocop:enable Layout/LineLength
{
answer_count:,
title: topic.title,
- question_text: p1.excerpt,
- question_likes: p1.like_count,
+ question_text: first_post.excerpt,
+ question_likes: first_post.like_count,
created_at: topic.created_at.as_json,
- question_modified: (p1.last_version_at || p1.created_at).as_json,
+ question_modified: (first_post.last_version_at || first_post.created_at).as_json,
username1: topic.user&.username,
user1_url: topic.user&.full_url,
- answer_json:,
+ answer_json: answers_json,
}
end
@@ -52,7 +50,9 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}"
- expect(response.body).to include(expected_schema_json(p2_single_answer_json))
+ expect(response.body).to include(
+ solved_schema_json(topic:, first_post: p1, answers_json: p2_single_answer_json),
+ )
end
it "does not include first post text in schema information when the guardian cannot see it" do
@@ -162,25 +162,24 @@ RSpec.describe TopicsController do
let(:p3) { Fabricate(:post, topic:) }
let(:p4) { Fabricate(:post, topic:) }
let(:solved_topic) { Fabricate(:solved_topic, topic:) }
-
- before do
- Fabricate(:topic_answer, solved_topic:, post: p2)
- Fabricate(:topic_answer, solved_topic:, post: p3)
- p4
- end
+ let!(:first_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p2) }
+ let!(:second_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p3) }
+ let!(:unaccepted_post) { p4 }
it "should include correct schema information " do
get "/t/#{topic.slug}/#{topic.id}"
two_accepted_answers_json =
',"acceptedAnswer":[%{answer_p2},%{answer_p3}]' %
- { answer_p2: answer_json(p2), answer_p3: answer_json(p3) }
+ { answer_p2: solved_answer_json(post: p2), answer_p3: solved_answer_json(post: p3) }
suggested_answer_json =
- ',"suggestedAnswer":[%{answer_p4}]' % { answer_p4: answer_json(p4) }
+ ',"suggestedAnswer":[%{answer_p4}]' % { answer_p4: solved_answer_json(post: p4) }
answers_json = "#{two_accepted_answers_json}#{suggested_answer_json}"
- expect(response.body).to include(expected_schema_json(answers_json, 3))
+ expect(response.body).to include(
+ solved_schema_json(topic:, first_post: p1, answers_json:, answer_count: 3),
+ )
end
end
end
@@ -188,13 +187,10 @@ RSpec.describe TopicsController do
describe "crawler schema modifiers" do
let(:crawler_env) { { "HTTP_USER_AGENT" => "Googlebot" } }
+ let(:parsed_crawler_body) { Nokogiri::HTML5.fragment(response.body) }
before { SiteSetting.allow_solved_on_all_topics = true }
- def parsed_crawler_body
- Nokogiri::HTML5.fragment(response.body)
- end
-
it "uses Question schema instead of DiscussionForumPosting when topic has replies" do
Fabricate(:post, topic:, user: Fabricate(:user))
@@ -300,13 +296,11 @@ RSpec.describe TopicsController do
let(:p3) { Fabricate(:post, topic:, cooked: "p3 cooked") }
let(:p4) { Fabricate(:post, topic:, cooked: "p4 cooked") }
let(:solved_topic) { Fabricate(:solved_topic, topic:) }
+ let!(:first_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p2) }
+ let!(:second_topic_answer) { Fabricate(:topic_answer, solved_topic:, post: p3) }
+ let!(:unaccepted_post) { p4 }
- before do
- SiteSetting.solved_allow_multiple_solutions = true
- Fabricate(:topic_answer, solved_topic:, post: p2)
- Fabricate(:topic_answer, solved_topic:, post: p3)
- p4
- end
+ before { SiteSetting.solved_allow_multiple_solutions = true }
it "should include two acceptedAnswers and a suggestedAnswer in qaschema" do
get "/t/#{topic.slug}/#{topic.id}", env: crawler_env
@@ -420,7 +414,9 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}"
- expect(response.body).to include(expected_schema_json(p2_single_answer_json))
+ expect(response.body).to include(
+ solved_schema_json(topic:, first_post: p1, answers_json: p2_single_answer_json),
+ )
end
it "doesn't include solved schema information when the topic has a different tag" do
@@ -431,7 +427,9 @@ RSpec.describe TopicsController do
get "/t/#{topic.slug}/#{topic.id}"
- expect(response.body).not_to include(expected_schema_json(p2_single_answer_json))
+ expect(response.body).not_to include(
+ solved_schema_json(topic:, first_post: p1, answers_json: p2_single_answer_json),
+ )
end
end
end
diff --git a/plugins/discourse-solved/spec/services/discourse_solved/enable_solved_badges_toggled_spec.rb b/plugins/discourse-solved/spec/services/discourse_solved/enable_solved_badges_toggled_spec.rb
index 5cb1102715f..209e582d24a 100644
--- a/plugins/discourse-solved/spec/services/discourse_solved/enable_solved_badges_toggled_spec.rb
+++ b/plugins/discourse-solved/spec/services/discourse_solved/enable_solved_badges_toggled_spec.rb
@@ -2,10 +2,7 @@
RSpec.describe DiscourseSolved::EnableSolvedBadgesToggled do
let(:badge_names) { DiscourseSolved::EnableSolvedBadgesToggled::BADGE_NAMES }
-
- def solved_badges
- Badge.where(name: badge_names)
- end
+ let(:solved_badges) { Badge.where(name: badge_names) }
describe "enabling" do
before { solved_badges.update_all(enabled: false) }
diff --git a/plugins/discourse-solved/spec/system/page_objects/pages/solved_topic.rb b/plugins/discourse-solved/spec/system/page_objects/pages/solved_topic.rb
new file mode 100644
index 00000000000..7e998faa127
--- /dev/null
+++ b/plugins/discourse-solved/spec/system/page_objects/pages/solved_topic.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ class SolvedTopic < PageObjects::Pages::Topic
+ UNACCEPTED_BUTTON_SELECTOR = ".post-action-menu__solved-unaccepted"
+ ACCEPTED_BUTTON_SELECTOR = ".post-action-menu__solved-accepted"
+ ACCEPTED_ANSWER_SELECTOR = ".accepted-answers .d-post-accordion-item"
+ ACCEPTED_ANSWER_CONTENT_SELECTOR = ".d-post-accordion-item__content"
+ SOLVER_SELECTOR = ".d-post-accordion-item__metadata .user-link"
+ ACCEPTER_SELECTOR = ".d-post-accordion-item__metadata .accepter-link"
+ QUOTE_TOGGLE_SELECTOR = ".d-post-accordion-item__toggle"
+
+ def visit_solution(topic:, post:)
+ visit_topic(topic, post_number: post.post_number)
+ end
+
+ def accept_solution(post)
+ within_post(post) { find(UNACCEPTED_BUTTON_SELECTOR).click }
+ self
+ end
+
+ def unaccept_solution(post)
+ within_post(post) { find(ACCEPTED_BUTTON_SELECTOR).click }
+ self
+ end
+
+ def has_accepted_solution?(post)
+ within_post(post) { has_css?(ACCEPTED_BUTTON_SELECTOR) } &&
+ has_css?(accepted_answer_selector(post))
+ end
+
+ def has_unaccepted_solution?(post)
+ within_post(post) { has_css?(UNACCEPTED_BUTTON_SELECTOR) }
+ end
+
+ def has_solution_content?(post, content:)
+ has_css?(
+ "#{accepted_answer_selector(post)} #{ACCEPTED_ANSWER_CONTENT_SELECTOR}",
+ text: content,
+ )
+ end
+
+ def has_no_solution_content?(post)
+ has_no_css?("#{accepted_answer_selector(post)} #{ACCEPTED_ANSWER_CONTENT_SELECTOR}")
+ end
+
+ def has_solution_authors?(post:, solver:, accepter:)
+ within(accepted_answer_selector(post)) do
+ has_css?(SOLVER_SELECTOR, text: solver.username) &&
+ has_css?(ACCEPTER_SELECTOR, text: accepter.username)
+ end
+ end
+
+ def has_solution_info?
+ has_css?(ACCEPTED_ANSWER_SELECTOR) && has_css?(SOLVER_SELECTOR) &&
+ has_css?(ACCEPTER_SELECTOR)
+ end
+
+ def has_no_solution_info?
+ has_no_css?(ACCEPTED_ANSWER_SELECTOR) && has_no_css?(SOLVER_SELECTOR) &&
+ has_no_css?(ACCEPTER_SELECTOR)
+ end
+
+ def toggle_solution_excerpt(post)
+ within(accepted_answer_selector(post)) { find(QUOTE_TOGGLE_SELECTOR).click }
+ self
+ end
+
+ def has_expanded_solution_excerpt?(post)
+ has_css?("#{accepted_answer_selector(post)}[data-expanded]")
+ end
+
+ def has_collapsed_solution_excerpt?(post)
+ has_css?("#{accepted_answer_selector(post)}:not([data-expanded])")
+ end
+
+ private
+
+ def accepted_answer_selector(post)
+ "#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post.post_number}']"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-solved/spec/system/solved_spec.rb b/plugins/discourse-solved/spec/system/solved_spec.rb
index 4f0422bdbfa..134d1163a29 100644
--- a/plugins/discourse-solved/spec/system/solved_spec.rb
+++ b/plugins/discourse-solved/spec/system/solved_spec.rb
@@ -11,14 +11,10 @@ describe "Solved" do
Fabricate(:post, topic:, user: solver, cooked: long_cooked)
end
- let(:topic_page) { PageObjects::Pages::Topic.new }
+ let(:topic_page) { PageObjects::Pages::SolvedTopic.new }
- UNACCEPTED_BUTTON_SELECTOR = ".post-action-menu__solved-unaccepted"
- ACCEPTED_BUTTON_SELECTOR = ".post-action-menu__solved-accepted"
ACCEPTED_ANSWER_SELECTOR = ".accepted-answers .d-post-accordion-item"
ACCEPTED_ANSWER_CONTENT_SELECTOR = ".d-post-accordion-item__content"
- SOLVER_SELECTOR = ".d-post-accordion-item__metadata .user-link"
- ACCEPTER_SELECTOR = ".d-post-accordion-item__metadata .accepter-link"
QUOTE_TOGGLE_SELECTOR = ".d-post-accordion-item__toggle"
QUOTE_JUMP_SELECTOR = ".d-post-accordion-item__jump"
@@ -32,30 +28,30 @@ describe "Solved" do
it "accepts post as solution and shows in OP" do
sign_in(accepter)
- visit_solver_post(2)
-
- verify_solution_unaccepted_state(2)
- accept_solution(2)
- verify_solution_accepted_state(2)
- verify_solution_content(2, "The answer is 42")
- verify_solver_and_accepter_info(2, solver, accepter)
- verify_solution_excerpt_expanded(2)
- toggle_solution_excerpt(2)
- verify_solution_excerpt_collapsed(2)
+ topic_page.visit_solution(topic:, post: solver_post)
+
+ expect(topic_page).to have_unaccepted_solution(solver_post)
+ topic_page.accept_solution(solver_post)
+ expect(topic_page).to have_accepted_solution(solver_post)
+ expect(topic_page).to have_solution_content(solver_post, content: "The answer is 42")
+ expect(topic_page).to have_solution_authors(post: solver_post, solver:, accepter:)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post)
+ topic_page.toggle_solution_excerpt(solver_post)
+ expect(topic_page).to have_collapsed_solution_excerpt(solver_post)
end
it "accepts and unaccepts post as solution" do
sign_in(accepter)
- visit_solver_post(2)
+ topic_page.visit_solution(topic:, post: solver_post)
- verify_solution_unaccepted_state(2)
- accept_solution(2)
- verify_solution_accepted_state(2)
- verify_solution_info_present
+ expect(topic_page).to have_unaccepted_solution(solver_post)
+ topic_page.accept_solution(solver_post)
+ expect(topic_page).to have_accepted_solution(solver_post)
+ expect(topic_page).to have_solution_info
- unaccept_solution(2)
- verify_solution_unaccepted_state(2)
- verify_solution_info_absent
+ topic_page.unaccept_solution(solver_post)
+ expect(topic_page).to have_unaccepted_solution(solver_post)
+ expect(topic_page).to have_no_solution_info
end
it "shows the solved post in user activity at /my/activity/solved" do
@@ -67,10 +63,8 @@ describe "Solved" do
end
describe "hidden overflow" do
- before do
- solved_topic = Fabricate(:solved_topic, topic:)
- Fabricate(:topic_answer, solved_topic:, post: solver_post, accepter:)
- end
+ fab!(:solved_topic) { Fabricate(:solved_topic, topic:) }
+ fab!(:topic_answer) { Fabricate(:topic_answer, solved_topic:, post: solver_post, accepter:) }
describe "when solved_quote_length = 0" do
before { SiteSetting.solved_quote_length = 0 }
@@ -124,11 +118,11 @@ describe "Solved" do
sign_in(accepter)
topic_page.visit_topic(topic)
- verify_solution_excerpt_expanded(2)
- toggle_solution_excerpt(2)
- verify_solution_excerpt_collapsed(2)
- toggle_solution_excerpt(2)
- verify_solution_excerpt_expanded(2)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post)
+ topic_page.toggle_solution_excerpt(solver_post)
+ expect(topic_page).to have_collapsed_solution_excerpt(solver_post)
+ topic_page.toggle_solution_excerpt(solver_post)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post)
end
describe "solution excerpt formatting" do
@@ -182,153 +176,80 @@ describe "Solved" do
it "accepts two posts as solutions and shows in OP" do
sign_in(accepter)
- visit_solver_post(2)
+ topic_page.visit_solution(topic:, post: solver_post)
- verify_solution_info_absent
- verify_solution_unaccepted_state(2)
- verify_solution_unaccepted_state(3)
+ expect(topic_page).to have_no_solution_info
+ expect(topic_page).to have_unaccepted_solution(solver_post)
+ expect(topic_page).to have_unaccepted_solution(solver_post2)
- accept_solution(2)
+ topic_page.accept_solution(solver_post)
- verify_solution_info_present
- verify_solution_accepted_state(2)
- verify_solution_unaccepted_state(3)
- verify_solution_excerpt_expanded(2)
- verify_solution_content(2, "The answer is 42")
- verify_solver_and_accepter_info(2, solver, accepter)
+ expect(topic_page).to have_solution_info
+ expect(topic_page).to have_accepted_solution(solver_post)
+ expect(topic_page).to have_unaccepted_solution(solver_post2)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post)
+ expect(topic_page).to have_solution_content(solver_post, content: "The answer is 42")
+ expect(topic_page).to have_solution_authors(post: solver_post, solver:, accepter:)
sign_in(accepter2)
- visit_solver_post(3)
-
- verify_solution_info_present
- verify_solution_accepted_state(2)
- verify_solution_unaccepted_state(3)
-
- accept_solution(3)
-
- verify_solution_info_present
- verify_solution_accepted_state(2)
- verify_solution_accepted_state(3)
- verify_solution_excerpt_expanded(2)
- verify_solution_excerpt_collapsed(3)
- verify_solver_and_accepter_info(2, solver, accepter)
- verify_solver_and_accepter_info(3, solver2, accepter2)
- verify_solution_content(2, "The answer is 42")
- verify_solution_content_missing(3)
- toggle_solution_excerpt(3)
- verify_solution_excerpt_expanded(3)
- verify_solution_content(3, "The answer is over 9000")
+ topic_page.visit_solution(topic:, post: solver_post2)
+
+ expect(topic_page).to have_solution_info
+ expect(topic_page).to have_accepted_solution(solver_post)
+ expect(topic_page).to have_unaccepted_solution(solver_post2)
+
+ topic_page.accept_solution(solver_post2)
+
+ expect(topic_page).to have_solution_info
+ expect(topic_page).to have_accepted_solution(solver_post)
+ expect(topic_page).to have_accepted_solution(solver_post2)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post)
+ expect(topic_page).to have_collapsed_solution_excerpt(solver_post2)
+ expect(topic_page).to have_solution_authors(post: solver_post, solver:, accepter:)
+ expect(topic_page).to have_solution_authors(
+ post: solver_post2,
+ solver: solver2,
+ accepter: accepter2,
+ )
+ expect(topic_page).to have_solution_content(solver_post, content: "The answer is 42")
+ expect(topic_page).to have_no_solution_content(solver_post2)
+ topic_page.toggle_solution_excerpt(solver_post2)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post2)
+ expect(topic_page).to have_solution_content(solver_post2, content: "The answer is over 9000")
end
it "correctly updates excerpts when removing one of many accepted solutions" do
sign_in(accepter)
- visit_solver_post(2)
-
- verify_solution_info_absent
-
- accept_solution(2)
- accept_solution(3)
-
- verify_solution_info_present
- verify_solution_accepted_state(2)
- verify_solution_accepted_state(3)
- verify_solution_excerpt_expanded(2)
- verify_solution_excerpt_collapsed(3)
- verify_solver_and_accepter_info(2, solver, accepter)
- verify_solver_and_accepter_info(3, solver2, accepter)
- verify_solution_content(2, "The answer is 42")
- verify_solution_content_missing(3)
- toggle_solution_excerpt(3)
- verify_solution_excerpt_expanded(3)
- verify_solution_content(3, "The answer is over 9000")
-
- unaccept_solution(2)
-
- verify_solution_info_present
- verify_solution_unaccepted_state(2)
- verify_solution_accepted_state(3)
- verify_solver_and_accepter_info(3, solver2, accepter)
- verify_solution_content(3, "The answer is over 9000")
-
- unaccept_solution(3)
- verify_solution_info_absent
+ topic_page.visit_solution(topic:, post: solver_post)
+
+ expect(topic_page).to have_no_solution_info
+
+ topic_page.accept_solution(solver_post)
+ topic_page.accept_solution(solver_post2)
+
+ expect(topic_page).to have_solution_info
+ expect(topic_page).to have_accepted_solution(solver_post)
+ expect(topic_page).to have_accepted_solution(solver_post2)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post)
+ expect(topic_page).to have_collapsed_solution_excerpt(solver_post2)
+ expect(topic_page).to have_solution_authors(post: solver_post, solver:, accepter:)
+ expect(topic_page).to have_solution_authors(post: solver_post2, solver: solver2, accepter:)
+ expect(topic_page).to have_solution_content(solver_post, content: "The answer is 42")
+ expect(topic_page).to have_no_solution_content(solver_post2)
+ topic_page.toggle_solution_excerpt(solver_post2)
+ expect(topic_page).to have_expanded_solution_excerpt(solver_post2)
+ expect(topic_page).to have_solution_content(solver_post2, content: "The answer is over 9000")
+
+ topic_page.unaccept_solution(solver_post)
+
+ expect(topic_page).to have_solution_info
+ expect(topic_page).to have_unaccepted_solution(solver_post)
+ expect(topic_page).to have_accepted_solution(solver_post2)
+ expect(topic_page).to have_solution_authors(post: solver_post2, solver: solver2, accepter:)
+ expect(topic_page).to have_solution_content(solver_post2, content: "The answer is over 9000")
+
+ topic_page.unaccept_solution(solver_post2)
+ expect(topic_page).to have_no_solution_info
end
end
-
- private
-
- def visit_solver_post(post_number)
- topic_page.visit_topic(topic, post_number:)
- end
-
- def accept_solution(post_number)
- within("article#post_#{post_number}") { find(UNACCEPTED_BUTTON_SELECTOR).click }
- end
-
- def unaccept_solution(post_number)
- within("article#post_#{post_number}") { find(ACCEPTED_BUTTON_SELECTOR).click }
- end
-
- def verify_solution_accepted_state(post_number)
- within("article#post_#{post_number}") do
- expect(topic_page).to have_css(ACCEPTED_BUTTON_SELECTOR)
- end
-
- expect(topic_page).to have_css("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']")
- end
-
- def verify_solution_unaccepted_state(post_number)
- within("article#post_#{post_number}") do
- expect(topic_page).to have_css(UNACCEPTED_BUTTON_SELECTOR)
- end
- end
-
- def verify_solution_content(post_number, content)
- within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
- expect(find(ACCEPTED_ANSWER_CONTENT_SELECTOR)).to have_content(content)
- end
- end
-
- def verify_solution_content_missing(post_number)
- within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
- expect(page).not_to have_css(ACCEPTED_ANSWER_CONTENT_SELECTOR)
- end
- end
-
- def verify_solver_and_accepter_info(post_number, solver, accepter)
- within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
- expect(find(SOLVER_SELECTOR)).to have_content(solver.username)
- expect(find(ACCEPTER_SELECTOR)).to have_content(accepter.username)
- end
- end
-
- def verify_solution_info_present
- expect(topic_page).to have_css(ACCEPTED_ANSWER_SELECTOR)
- expect(topic_page).to have_css(SOLVER_SELECTOR)
- expect(topic_page).to have_css(ACCEPTER_SELECTOR)
- end
-
- def verify_solution_info_absent
- expect(topic_page).to have_no_css(ACCEPTED_ANSWER_SELECTOR)
- expect(topic_page).to have_no_css(SOLVER_SELECTOR)
- expect(topic_page).to have_no_css(ACCEPTER_SELECTOR)
- end
-
- def toggle_solution_excerpt(post_number)
- within("#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']") do
- find(QUOTE_TOGGLE_SELECTOR).click
- end
- end
-
- def verify_solution_excerpt_expanded(post_number)
- expect(topic_page).to have_css(
- "#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}'][data-expanded]",
- )
- end
-
- def verify_solution_excerpt_collapsed(post_number)
- expect(topic_page).to have_css(
- "#{ACCEPTED_ANSWER_SELECTOR}[data-post='#{post_number}']:not([data-expanded])",
- )
- end
end
diff --git a/plugins/discourse-subscriptions/spec/requests/user/subscriptions_controller_spec.rb b/plugins/discourse-subscriptions/spec/requests/user/subscriptions_controller_spec.rb
index 13ade9353de..a9e58e94496 100644
--- a/plugins/discourse-subscriptions/spec/requests/user/subscriptions_controller_spec.rb
+++ b/plugins/discourse-subscriptions/spec/requests/user/subscriptions_controller_spec.rb
@@ -6,14 +6,6 @@ RSpec.describe DiscourseSubscriptions::User::SubscriptionsController do
SiteSetting.discourse_subscriptions_secret_key = "secret-key"
end
- def create_price(id, product)
- price = { id: id, product: product }
- def price.id
- self[:id]
- end
- price
- end
-
it "is a subclass of ApplicationController" do
expect(DiscourseSubscriptions::User::SubscriptionsController < ::ApplicationController).to eq(
true,
@@ -43,12 +35,12 @@ RSpec.describe DiscourseSubscriptions::User::SubscriptionsController do
let(:customer) do
Fabricate(:customer, user_id: user.id, customer_id: "cus_23456", product_id: "prod_123")
end
-
- before do
- sign_in(user)
+ let!(:subscription) do
Fabricate(:subscription, customer_id: customer.id, external_id: "sub_10z")
end
+ before { sign_in(user) }
+
describe "index" do
plans_json =
File.read(
@@ -97,11 +89,25 @@ RSpec.describe DiscourseSubscriptions::User::SubscriptionsController do
# Build the first page of 100 prices that do NOT include the desired price.
prices_page_1 =
(1..100).map do |i|
- create_price("price_#{i}", { id: "prod_dummy", name: "Dummy Product #{i}" })
+ ::Stripe::Price.construct_from(
+ id: "price_#{i}",
+ product: {
+ id: "prod_dummy",
+ name: "Dummy Product #{i}",
+ },
+ )
end
# Second page containing the desired price.
- prices_page_2 = [create_price("price_200", { id: "prod_200", name: "Matching Product" })]
+ prices_page_2 = [
+ ::Stripe::Price.construct_from(
+ id: "price_200",
+ product: {
+ id: "prod_200",
+ name: "Matching Product",
+ },
+ ),
+ ]
::Stripe::Price
.expects(:list)
diff --git a/plugins/discourse-topic-voting/spec/integration/enable_topic_voting_badges_spec.rb b/plugins/discourse-topic-voting/spec/integration/enable_topic_voting_badges_spec.rb
index 6cfab3420f2..20844325fe2 100644
--- a/plugins/discourse-topic-voting/spec/integration/enable_topic_voting_badges_spec.rb
+++ b/plugins/discourse-topic-voting/spec/integration/enable_topic_voting_badges_spec.rb
@@ -3,14 +3,10 @@
RSpec.describe "Enable Topic Voting badges by default upcoming change" do
let(:badge_names) { DiscourseTopicVoting::BADGE_NAMES }
- def reseed_topic_voting_badges
- Badge.where(name: badge_names).delete_all
- load Rails.root.join("plugins/discourse-topic-voting/db/fixtures/001_badges.rb") # rubocop:disable Discourse/Plugins/UseRequireRelative
- end
-
describe "seeding the Topic Voting badges on a new site" do
it "enables the badges by default" do
- reseed_topic_voting_badges
+ Badge.where(name: badge_names).delete_all
+ load Rails.root.join("plugins/discourse-topic-voting/db/fixtures/001_badges.rb") # rubocop:disable Discourse/Plugins/UseRequireRelative
expect(Badge.where(name: badge_names).pluck(:enabled)).to all(eq(true))
end
diff --git a/plugins/discourse-topic-voting/spec/jobs/backfill_badges_spec.rb b/plugins/discourse-topic-voting/spec/jobs/backfill_badges_spec.rb
index b9923f9fd52..2585d9f137b 100644
--- a/plugins/discourse-topic-voting/spec/jobs/backfill_badges_spec.rb
+++ b/plugins/discourse-topic-voting/spec/jobs/backfill_badges_spec.rb
@@ -12,14 +12,6 @@ RSpec.describe Jobs::DiscourseTopicVoting::BackfillBadges do
before { Badge.where(name: DiscourseTopicVoting::BADGE_NAMES).update_all(enabled: true) }
- def vote!(topic:, count:)
- count.times { Fabricate(:topic_voting_votes, topic:) }
- end
-
- def user_badge_count(user, badge)
- UserBadge.where(user:, badge:).count
- end
-
describe "seeded badges" do
it "seeds four badges with correct attributes" do
expect(daydreamer.badge_type_id).to eq(BadgeType::Bronze)
@@ -40,47 +32,47 @@ RSpec.describe Jobs::DiscourseTopicVoting::BackfillBadges do
describe "#execute" do
it "grants Daydreamer for a single vote" do
- vote!(topic:, count: 1)
+ Fabricate(:topic_voting_votes, topic:)
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(0)
expect(UserBadge.find_by(user_id: topic_author.id, badge_id: daydreamer.id).post_id).to eq(
first_post.id,
)
end
it "grants Brainstormer at 5 votes" do
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(1)
- expect(user_badge_count(topic_author, innovator)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: innovator).count).to eq(0)
end
it "grants Innovator at 15 votes" do
- vote!(topic:, count: 15)
+ 15.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(1)
- expect(user_badge_count(topic_author, innovator)).to eq(1)
- expect(user_badge_count(topic_author, visionary)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: innovator).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: visionary).count).to eq(0)
end
it "grants Visionary at 25 votes" do
- vote!(topic:, count: 25)
+ 25.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(1)
- expect(user_badge_count(topic_author, innovator)).to eq(1)
- expect(user_badge_count(topic_author, visionary)).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: innovator).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: visionary).count).to eq(1)
end
it "does not count self-votes toward the threshold" do
@@ -88,108 +80,108 @@ RSpec.describe Jobs::DiscourseTopicVoting::BackfillBadges do
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
end
it "ignores self-votes when tallying" do
Fabricate(:topic_voting_votes, topic:, user: topic_author)
- vote!(topic:, count: 4)
+ 4.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(0)
end
it "grants the badge separately for each qualifying topic (multi-grant)" do
other_topic = Fabricate(:topic, user: topic_author)
other_first_post = Fabricate(:post, topic: other_topic, user: topic_author)
- vote!(topic:, count: 1)
- vote!(topic: other_topic, count: 1)
+ Fabricate(:topic_voting_votes, topic:)
+ Fabricate(:topic_voting_votes, topic: other_topic)
described_class.new.execute(topic_id: topic.id)
described_class.new.execute(topic_id: other_topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(2)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(2)
grant_post_ids =
UserBadge.where(user_id: topic_author.id, badge_id: daydreamer.id).pluck(:post_id)
expect(grant_post_ids).to contain_exactly(first_post.id, other_first_post.id)
end
it "is idempotent for the same topic" do
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(1)
end
it "does not grant when the topic is deleted" do
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
topic.trash!
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
- expect(user_badge_count(topic_author, brainstormer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(0)
end
it "does not grant for non-regular archetypes" do
topic.update_columns(archetype: Archetype.private_message, category_id: nil)
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
end
it "does nothing when badges are disabled site-wide" do
SiteSetting.enable_badges = false
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
end
it "does nothing when a badge is disabled" do
daydreamer.update!(enabled: false)
- vote!(topic:, count: 1)
+ Fabricate(:topic_voting_votes, topic:)
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
end
it "does not grant for unlisted topics" do
topic.update!(visible: false)
- vote!(topic:, count: 1)
+ Fabricate(:topic_voting_votes, topic:)
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
end
it "does not grant when the category does not allow badges" do
topic.category.update!(allow_badges: false)
- vote!(topic:, count: 1)
+ Fabricate(:topic_voting_votes, topic:)
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(0)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(0)
end
it "suppresses the granted-badge notification when the qualifying votes are older than 2 weeks" do
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
DiscourseTopicVoting::Vote.update_all(created_at: 3.weeks.ago)
described_class.new.execute(topic_id: topic.id)
- expect(user_badge_count(topic_author, daydreamer)).to eq(1)
- expect(user_badge_count(topic_author, brainstormer)).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: daydreamer).count).to eq(1)
+ expect(UserBadge.where(user: topic_author, badge: brainstormer).count).to eq(1)
expect(
UserBadge.where(user: topic_author, badge: [daydreamer, brainstormer]).pluck(
:notification_id,
@@ -198,7 +190,7 @@ RSpec.describe Jobs::DiscourseTopicVoting::BackfillBadges do
end
it "still notifies when the qualifying votes are recent" do
- vote!(topic:, count: 5)
+ 5.times { Fabricate(:topic_voting_votes, topic:) }
described_class.new.execute(topic_id: topic.id)
@@ -208,9 +200,9 @@ RSpec.describe Jobs::DiscourseTopicVoting::BackfillBadges do
end
it "only notifies for the highest tier reached when older tiers were crossed long ago" do
- vote!(topic:, count: 4)
+ 4.times { Fabricate(:topic_voting_votes, topic:) }
DiscourseTopicVoting::Vote.update_all(created_at: 3.weeks.ago)
- vote!(topic:, count: 1)
+ Fabricate(:topic_voting_votes, topic:)
described_class.new.execute(topic_id: topic.id)
diff --git a/plugins/discourse-topic-voting/spec/lib/user_merger_spec.rb b/plugins/discourse-topic-voting/spec/lib/user_merger_spec.rb
index 9847bfddfe1..7c4b816c2aa 100644
--- a/plugins/discourse-topic-voting/spec/lib/user_merger_spec.rb
+++ b/plugins/discourse-topic-voting/spec/lib/user_merger_spec.rb
@@ -8,11 +8,9 @@ describe DiscourseTopicVoting::UserMerger do
fab!(:topic3, :topic)
fab!(:topic4, :topic)
- before { SiteSetting.topic_voting_enabled = true }
+ subject(:user_merger) { UserMerger.new(source_user, target_user) }
- def merge_users!
- UserMerger.new(source_user, target_user).merge!
- end
+ before { SiteSetting.topic_voting_enabled = true }
context "when merging users with votes" do
it "transfers source user votes to target user" do
@@ -22,7 +20,7 @@ describe DiscourseTopicVoting::UserMerger do
expect(source_user.vote_count).to eq(2)
expect(target_user.vote_count).to eq(0)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.vote_count).to eq(2)
@@ -36,7 +34,7 @@ describe DiscourseTopicVoting::UserMerger do
DiscourseTopicVoting::Vote.create!(user: target_user, topic: topic1)
DiscourseTopicVoting::Vote.create!(user: source_user, topic: topic2)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.vote_count).to eq(2)
@@ -53,7 +51,7 @@ describe DiscourseTopicVoting::UserMerger do
DiscourseTopicVoting::Vote.create!(user: target_user, topic: topic2)
DiscourseTopicVoting::Vote.create!(user: source_user, topic: topic3)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.vote_count).to eq(3)
@@ -72,7 +70,7 @@ describe DiscourseTopicVoting::UserMerger do
DiscourseTopicVoting::Vote.create!(user: source_user, topic: topic1, archive: true)
DiscourseTopicVoting::Vote.create!(user: source_user, topic: topic2, archive: false)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.topics_with_vote.pluck(:topic_id)).to contain_exactly(topic2.id)
@@ -90,7 +88,7 @@ describe DiscourseTopicVoting::UserMerger do
expect(topic1.topic_vote_count.votes_count).to eq(1)
expect(topic2.topic_vote_count.votes_count).to eq(2)
- merge_users!
+ user_merger.merge!
topic1.reload
topic2.reload
@@ -111,7 +109,7 @@ describe DiscourseTopicVoting::UserMerger do
expect(source_user.reached_voting_limit?).to eq(true)
expect(target_user.reached_voting_limit?).to eq(false)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.vote_count).to eq(3)
@@ -121,14 +119,14 @@ describe DiscourseTopicVoting::UserMerger do
it "handles merge when source user has no votes" do
DiscourseTopicVoting::Vote.create!(user: target_user, topic: topic1)
- expect { merge_users! }.not_to raise_error
+ expect { user_merger.merge! }.not_to raise_error
target_user.reload
expect(target_user.vote_count).to eq(1)
end
it "handles merge when both users have no votes" do
- expect { merge_users! }.not_to raise_error
+ expect { user_merger.merge! }.not_to raise_error
target_user.reload
expect(target_user.vote_count).to eq(0)
@@ -140,7 +138,7 @@ describe DiscourseTopicVoting::UserMerger do
DiscourseTopicVoting::Vote.create!(user: target_user, topic: topic1)
DiscourseTopicVoting::Vote.create!(user: target_user, topic: topic2)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.vote_count).to eq(2)
@@ -152,7 +150,7 @@ describe DiscourseTopicVoting::UserMerger do
vote = DiscourseTopicVoting::Vote.create!(user: source_user, topic: topic1)
vote.update_column(:created_at, created_at)
- merge_users!
+ user_merger.merge!
merged_vote = DiscourseTopicVoting::Vote.find_by(user_id: target_user.id, topic_id: topic1.id)
expect(merged_vote.created_at.to_i).to eq(created_at.to_i)
@@ -162,7 +160,7 @@ describe DiscourseTopicVoting::UserMerger do
DiscourseTopicVoting::Vote.create!(user: source_user, topic: topic1, archive: true)
DiscourseTopicVoting::Vote.create!(user: target_user, topic: topic1, archive: false)
- merge_users!
+ user_merger.merge!
target_user.reload
expect(target_user.topics_with_vote.pluck(:topic_id)).to contain_exactly(topic1.id)
@@ -185,7 +183,7 @@ describe DiscourseTopicVoting::UserMerger do
expect(topic1.topic_vote_count.votes_count).to eq(3)
expect(topic2.topic_vote_count.votes_count).to eq(1)
- merge_users!
+ user_merger.merge!
topic1.reload
topic2.reload
diff --git a/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/enable_topic_voting_badges_toggled_spec.rb b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/enable_topic_voting_badges_toggled_spec.rb
index baf76c36cc4..5d425f190e3 100644
--- a/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/enable_topic_voting_badges_toggled_spec.rb
+++ b/plugins/discourse-topic-voting/spec/services/discourse_topic_voting/enable_topic_voting_badges_toggled_spec.rb
@@ -2,10 +2,7 @@
RSpec.describe DiscourseTopicVoting::EnableTopicVotingBadgesToggled do
let(:badge_names) { DiscourseTopicVoting::BADGE_NAMES }
-
- def topic_voting_badges
- Badge.where(name: badge_names)
- end
+ let(:topic_voting_badges) { Badge.where(name: badge_names) }
describe "enabling" do
before { topic_voting_badges.update_all(enabled: false) }
diff --git a/plugins/discourse-workflows/spec/db/migrate/copy_workflow_trigger_category_id_to_category_ids_spec.rb b/plugins/discourse-workflows/spec/db/migrate/copy_workflow_trigger_category_id_to_category_ids_spec.rb
deleted file mode 100644
index f914d657b3f..00000000000
--- a/plugins/discourse-workflows/spec/db/migrate/copy_workflow_trigger_category_id_to_category_ids_spec.rb
+++ /dev/null
@@ -1,185 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-workflows/db/migrate/20260722140536_copy_workflow_trigger_category_id_to_category_ids",
- )
-
-RSpec.describe CopyWorkflowTriggerCategoryIdToCategoryIds do
- subject(:migration) { described_class.new }
-
- fab!(:workflow, :discourse_workflows_workflow)
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- def build_node(type:, parameters:, id: "node-1")
- { "id" => id, "type" => type, "parameters" => parameters }
- end
-
- def set_workflow_nodes(nodes)
- workflow.update_columns(nodes: nodes)
- end
-
- def workflow_nodes
- workflow.reload.nodes
- end
-
- it "copies a scalar category_id into a category_ids array and keeps the legacy key" do
- set_workflow_nodes(
- [build_node(type: "trigger:topic_created", parameters: { "category_id" => "12" })],
- )
-
- migration.up
-
- parameters = workflow_nodes.first["parameters"]
- expect(parameters["category_ids"]).to eq(["12"])
- expect(parameters["category_id"]).to eq("12")
- expect(parameters).not_to have_key("include_subcategories")
- end
-
- it "preserves numeric and expression category_id values verbatim" do
- set_workflow_nodes(
- [
- build_node(type: "trigger:topic_created", parameters: { "category_id" => 12 }, id: "a"),
- build_node(
- type: "trigger:post_created",
- parameters: {
- "category_id" => "=$json.category_id",
- },
- id: "b",
- ),
- ],
- )
-
- migration.up
-
- expect(workflow_nodes.map { |node| node["parameters"]["category_ids"] }).to eq(
- [[12], ["=$json.category_id"]],
- )
- end
-
- it "overwrites an explicit null category_ids with the copied value" do
- set_workflow_nodes(
- [
- build_node(
- type: "trigger:topic_created",
- parameters: {
- "category_id" => "12",
- "category_ids" => nil,
- },
- ),
- ],
- )
-
- migration.up
-
- expect(workflow_nodes.first["parameters"]["category_ids"]).to eq(["12"])
- end
-
- it "does not add category_ids for a blank category_id" do
- set_workflow_nodes(
- [build_node(type: "trigger:topic_created", parameters: { "category_id" => "" })],
- )
-
- migration.up
-
- parameters = workflow_nodes.first["parameters"]
- expect(parameters).not_to have_key("category_ids")
- expect(parameters["category_id"]).to eq("")
- end
-
- it "does not touch include_subcategories" do
- set_workflow_nodes(
- [
- build_node(type: "trigger:topic_closed", parameters: { "category_id" => "3" }, id: "a"),
- build_node(
- type: "trigger:topic_created",
- parameters: {
- "category_id" => "3",
- "include_subcategories" => false,
- },
- id: "b",
- ),
- ],
- )
-
- migration.up
-
- nodes_by_id = workflow_nodes.index_by { |node| node["id"] }
- expect(nodes_by_id["a"]["parameters"]).not_to have_key("include_subcategories")
- expect(nodes_by_id["b"]["parameters"]["include_subcategories"]).to eq(false)
- end
-
- it "leaves non-trigger nodes and already-migrated nodes untouched" do
- nodes = [
- build_node(type: "action:topic", parameters: { "category_id" => "5" }, id: "a"),
- build_node(
- type: "trigger:topic_created",
- parameters: {
- "category_id" => "5",
- "category_ids" => ["7"],
- },
- id: "b",
- ),
- ]
- set_workflow_nodes(nodes)
-
- migration.up
-
- expect(workflow_nodes).to eq(nodes)
- end
-
- it "is idempotent and preserves node ordering" do
- set_workflow_nodes(
- [
- build_node(type: "trigger:topic_created", parameters: { "category_id" => "12" }, id: "a"),
- build_node(type: "action:post", parameters: { "operation" => "create" }, id: "b"),
- ],
- )
-
- migration.up
- first_pass = workflow_nodes
- migration.up
-
- expect(workflow_nodes).to eq(first_pass)
- expect(workflow_nodes.map { |node| node["id"] }).to eq(%w[a b])
- end
-
- it "migrates workflow version snapshots" do
- node = build_node(type: "trigger:topic_created", parameters: { "category_id" => "12" })
- DiscourseWorkflows::WorkflowVersion.where(workflow_id: workflow.id).update_all(nodes: [node])
-
- migration.up
-
- version_nodes = DiscourseWorkflows::WorkflowVersion.find_by(workflow_id: workflow.id).nodes
- expect(version_nodes.first["parameters"]["category_ids"]).to eq(["12"])
- end
-
- it "migrates execution data snapshots" do
- node = build_node(type: "trigger:topic_created", parameters: { "category_id" => "12" })
- execution_data = Fabricate(:discourse_workflows_execution_data)
- execution_data.update_columns(workflow_data: { "nodes" => [node] })
-
- migration.up
-
- reloaded_nodes = execution_data.reload.workflow_data["nodes"]
- expect(reloaded_nodes.first["parameters"]["category_ids"]).to eq(["12"])
- end
-
- it "migrates webhook workflow snapshots" do
- node = build_node(type: "trigger:topic_created", parameters: { "category_id" => "12" })
- DB.exec(<<~SQL, workflow_id: workflow.id, snapshot: { "nodes" => [node] }.to_json)
- INSERT INTO discourse_workflows_webhooks
- (workflow_id, node_name, webhook_path, http_method, workflow_snapshot)
- VALUES (:workflow_id, 'Webhook', '/spec-webhook', 'POST', :snapshot::jsonb)
- SQL
-
- migration.up
-
- snapshot =
- DB.query_single(
- "SELECT workflow_snapshot FROM discourse_workflows_webhooks WHERE workflow_id = :workflow_id",
- workflow_id: workflow.id,
- ).first
- expect(snapshot["nodes"].first["parameters"]["category_ids"]).to eq(["12"])
- end
-end
diff --git a/plugins/discourse-workflows/spec/db/migrate/rename_discourse_workflows_enabled_site_setting_spec.rb b/plugins/discourse-workflows/spec/db/migrate/rename_discourse_workflows_enabled_site_setting_spec.rb
deleted file mode 100644
index 80118454a35..00000000000
--- a/plugins/discourse-workflows/spec/db/migrate/rename_discourse_workflows_enabled_site_setting_spec.rb
+++ /dev/null
@@ -1,57 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-workflows/db/migrate/20260708095336_rename_discourse_workflows_enabled_site_setting",
- )
-
-RSpec.describe RenameDiscourseWorkflowsEnabledSiteSetting do
- subject(:migration) { described_class.new }
-
- let(:connection) { ActiveRecord::Base.connection }
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- before { delete_workflow_settings }
-
- after { delete_workflow_settings }
-
- def delete_workflow_settings
- connection.execute(<<~SQL)
- DELETE FROM site_settings
- WHERE name IN ('discourse_workflows_enabled', 'enable_discourse_workflows')
- SQL
- end
-
- def store_setting(name, value)
- connection.execute(<<~SQL)
- INSERT INTO site_settings (name, data_type, value, created_at, updated_at)
- VALUES ('#{name}', 5, '#{value}', NOW(), NOW())
- SQL
- end
-
- def setting_value(name)
- DB.query_single("SELECT value FROM site_settings WHERE name = :name", name: name).first
- end
-
- it "preserves enabled customer opt-ins" do
- store_setting("discourse_workflows_enabled", "t")
-
- migration.up
-
- aggregate_failures do
- expect(setting_value("discourse_workflows_enabled")).to be_nil
- expect(setting_value("enable_discourse_workflows")).to eq("t")
- end
- end
-
- it "restores the old setting name on rollback" do
- store_setting("enable_discourse_workflows", "t")
-
- migration.down
-
- aggregate_failures do
- expect(setting_value("enable_discourse_workflows")).to be_nil
- expect(setting_value("discourse_workflows_enabled")).to eq("t")
- end
- end
-end
diff --git a/plugins/discourse-workflows/spec/db/post_migrate/remove_workflow_trigger_category_id_from_trigger_nodes_spec.rb b/plugins/discourse-workflows/spec/db/post_migrate/remove_workflow_trigger_category_id_from_trigger_nodes_spec.rb
deleted file mode 100644
index f30edd98827..00000000000
--- a/plugins/discourse-workflows/spec/db/post_migrate/remove_workflow_trigger_category_id_from_trigger_nodes_spec.rb
+++ /dev/null
@@ -1,136 +0,0 @@
-# frozen_string_literal: true
-
-require Rails.root.join(
- "plugins/discourse-workflows/db/post_migrate/20260722140539_remove_workflow_trigger_category_id_from_trigger_nodes",
- )
-
-RSpec.describe RemoveWorkflowTriggerCategoryIdFromTriggerNodes do
- subject(:migration) { described_class.new }
-
- fab!(:workflow, :discourse_workflows_workflow)
-
- around { |example| ActiveRecord::Migration.suppress_messages { example.run } }
-
- def build_node(type:, parameters:, id: "node-1")
- { "id" => id, "type" => type, "parameters" => parameters }
- end
-
- def set_workflow_nodes(nodes)
- workflow.update_columns(nodes: nodes)
- end
-
- def workflow_nodes
- workflow.reload.nodes
- end
-
- it "strips category_id from already-copied trigger nodes" do
- set_workflow_nodes(
- [
- build_node(
- type: "trigger:topic_created",
- parameters: {
- "category_id" => "12",
- "category_ids" => ["12"],
- },
- ),
- ],
- )
-
- migration.up
-
- parameters = workflow_nodes.first["parameters"]
- expect(parameters).not_to have_key("category_id")
- expect(parameters["category_ids"]).to eq(["12"])
- end
-
- it "copies then strips rows written by pre-rename code" do
- set_workflow_nodes(
- [build_node(type: "trigger:topic_closed", parameters: { "category_id" => "12" })],
- )
-
- migration.up
-
- parameters = workflow_nodes.first["parameters"]
- expect(parameters).not_to have_key("category_id")
- expect(parameters["category_ids"]).to eq(["12"])
- expect(parameters).not_to have_key("include_subcategories")
- end
-
- it "copies over an explicit null category_ids before stripping" do
- set_workflow_nodes(
- [
- build_node(
- type: "trigger:topic_created",
- parameters: {
- "category_id" => "12",
- "category_ids" => nil,
- },
- ),
- ],
- )
-
- migration.up
-
- parameters = workflow_nodes.first["parameters"]
- expect(parameters).not_to have_key("category_id")
- expect(parameters["category_ids"]).to eq(["12"])
- end
-
- it "drops a blank category_id without adding category_ids" do
- set_workflow_nodes(
- [build_node(type: "trigger:topic_created", parameters: { "category_id" => "" })],
- )
-
- migration.up
-
- parameters = workflow_nodes.first["parameters"]
- expect(parameters).not_to have_key("category_id")
- expect(parameters).not_to have_key("category_ids")
- end
-
- it "leaves non-trigger nodes untouched" do
- nodes = [build_node(type: "action:topic", parameters: { "category_id" => "5" })]
- set_workflow_nodes(nodes)
-
- migration.up
-
- expect(workflow_nodes).to eq(nodes)
- end
-
- it "strips the legacy key from version, execution, and webhook snapshots" do
- node =
- build_node(
- type: "trigger:topic_created",
- parameters: {
- "category_id" => "12",
- "category_ids" => ["12"],
- },
- )
- DiscourseWorkflows::WorkflowVersion.where(workflow_id: workflow.id).update_all(nodes: [node])
- execution_data = Fabricate(:discourse_workflows_execution_data)
- execution_data.update_columns(workflow_data: { "nodes" => [node] })
- DB.exec(<<~SQL, workflow_id: workflow.id, snapshot: { "nodes" => [node] }.to_json)
- INSERT INTO discourse_workflows_webhooks
- (workflow_id, node_name, webhook_path, http_method, workflow_snapshot)
- VALUES (:workflow_id, 'Webhook', '/spec-webhook', 'POST', :snapshot::jsonb)
- SQL
-
- migration.up
-
- version_parameters =
- DiscourseWorkflows::WorkflowVersion.find_by(workflow_id: workflow.id).nodes.first[
- "parameters"
- ]
- expect(version_parameters).not_to have_key("category_id")
-
- execution_parameters = execution_data.reload.workflow_data["nodes"].first["parameters"]
- expect(execution_parameters).not_to have_key("category_id")
-
- webhook_snapshot =
- DB.query_single(
- "SELECT workflow_snapshot FROM discourse_workflows_webhooks WHERE workflow_id = :workflow_id",
- workflow_id: workflow.id,
- ).first
- expect(webhook_snapshot["nodes"].first["parameters"]).not_to have_key("category_id")
- end
-end
diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb
index 84aaf5bdf06..5f8322a09b6 100644
--- a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb
+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/execute_manual_workflow_spec.rb
@@ -3,18 +3,6 @@
RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
fab!(:admin)
- def pending_execution(workflow:, trigger_node_id: "trigger-1", trigger_data: {})
- DiscourseWorkflows::Execution.create_pending_manual!(
- workflow: workflow,
- trigger_node_id: trigger_node_id,
- trigger_data: trigger_data,
- )
- end
-
- def execute_job(execution_id, user_id: admin.id)
- described_class.new.execute(execution_id: execution_id, user_id: user_id)
- end
-
it "claims and completes a pending execution without creating a duplicate" do
graph =
build_workflow_graph do |builder|
@@ -23,9 +11,17 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
builder.chain "trigger-1", "log-1"
end
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
- execution = pending_execution(workflow: workflow)
+ execution =
+ DiscourseWorkflows::Execution.create_pending_manual!(
+ workflow:,
+ trigger_node_id: "trigger-1",
+ trigger_data: {
+ },
+ )
- expect do execute_job(execution.id) end.not_to change { DiscourseWorkflows::Execution.count }
+ expect do
+ described_class.new.execute(execution_id: execution.id, user_id: admin.id)
+ end.not_to change { DiscourseWorkflows::Execution.count }
execution.reload
expect(execution.status).to eq("success")
@@ -39,9 +35,15 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
it "skips the execution when the plugin is disabled" do
SiteSetting.enable_discourse_workflows = false
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
- execution = pending_execution(workflow: workflow)
+ execution =
+ DiscourseWorkflows::Execution.create_pending_manual!(
+ workflow:,
+ trigger_node_id: "trigger-1",
+ trigger_data: {
+ },
+ )
- execute_job(execution.id)
+ described_class.new.execute(execution_id: execution.id, user_id: admin.id)
execution.reload
expect(execution.status).to eq("skipped")
@@ -50,11 +52,17 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
it "leaves a non-pending execution untouched" do
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
- execution = pending_execution(workflow: workflow)
+ execution =
+ DiscourseWorkflows::Execution.create_pending_manual!(
+ workflow:,
+ trigger_node_id: "trigger-1",
+ trigger_data: {
+ },
+ )
execution.update!(status: :running)
before_updated_at = execution.updated_at
- execute_job(execution.id)
+ described_class.new.execute(execution_id: execution.id, user_id: admin.id)
execution.reload
expect(execution.status).to eq("running")
@@ -62,7 +70,9 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
end
it "no-ops when the execution is missing" do
- expect { execute_job(-1) }.not_to change { DiscourseWorkflows::Execution.count }
+ expect { described_class.new.execute(execution_id: -1, user_id: admin.id) }.not_to change {
+ DiscourseWorkflows::Execution.count
+ }
end
it "runs the stored draft snapshot instead of the current or published workflow" do
@@ -81,10 +91,16 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
builder.chain "trigger-1", "draft-log"
end
workflow.update!(nodes: draft_graph[:nodes], connections: draft_graph[:connections])
- execution = pending_execution(workflow: workflow)
+ execution =
+ DiscourseWorkflows::Execution.create_pending_manual!(
+ workflow:,
+ trigger_node_id: "trigger-1",
+ trigger_data: {
+ },
+ )
workflow.update!(nodes: published_graph[:nodes], connections: published_graph[:connections])
- execute_job(execution.id)
+ described_class.new.execute(execution_id: execution.id, user_id: admin.id)
expect(execution.reload.execution_data.steps_array.map { |step| step["node_id"] }).to include(
"draft-log",
@@ -94,9 +110,17 @@ RSpec.describe Jobs::DiscourseWorkflows::ExecuteManualWorkflow do
it "records errors on the existing execution" do
graph = build_workflow_graph { |builder| builder.node "trigger-1", "trigger:manual" }
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
- execution = pending_execution(workflow: workflow, trigger_node_id: "missing-trigger")
+ execution =
+ DiscourseWorkflows::Execution.create_pending_manual!(
+ workflow:,
+ trigger_node_id: "missing-trigger",
+ trigger_data: {
+ },
+ )
- expect do execute_job(execution.id) end.not_to change { DiscourseWorkflows::Execution.count }
+ expect do
+ described_class.new.execute(execution_id: execution.id, user_id: admin.id)
+ end.not_to change { DiscourseWorkflows::Execution.count }
expect(execution.reload).to have_attributes(status: "error", error: include("missing-trigger"))
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb
index 55f2d6dee1b..d44b56e31ff 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb
@@ -6,7 +6,12 @@ RSpec.describe DiscourseWorkflows::ActiveWebhooks do
before { described_class.reset_for_tests! }
after { described_class.reset_for_tests! }
- def make_workflow(path:, http_method:, webhook_id: nil)
+ let(:webhook_path) { "hooks/inbound" }
+ let(:http_method) { "POST" }
+ let(:webhook_id) { nil }
+ let(:workflow) { activate_workflow(path: webhook_path, http_method:, webhook_id:) }
+
+ def activate_workflow(path:, http_method:, webhook_id: nil)
graph =
build_workflow_graph do |g|
g.node "webhook-1",
@@ -28,7 +33,7 @@ RSpec.describe DiscourseWorkflows::ActiveWebhooks do
describe ".find" do
it "matches static paths exactly with empty path_params" do
- make_workflow(path: "hooks/inbound", http_method: "POST")
+ workflow
result = described_class.find(method: "POST", path: "hooks/inbound", test_webhook: false)
@@ -37,21 +42,26 @@ RSpec.describe DiscourseWorkflows::ActiveWebhooks do
end
it "returns nil when the method does not match" do
- make_workflow(path: "hooks/inbound", http_method: "POST")
+ workflow
expect(
described_class.find(method: "GET", path: "hooks/inbound", test_webhook: false),
).to be_nil
end
- it "matches dynamic paths by webhook_id prefix and captures path params" do
- make_workflow(path: "users/:id/posts", http_method: "GET", webhook_id: "abcd-1234")
+ context "with a dynamic webhook path" do
+ let(:webhook_path) { "users/:id/posts" }
+ let(:http_method) { "GET" }
+ let(:webhook_id) { "abcd-1234" }
- result =
- described_class.find(method: "GET", path: "abcd-1234/users/42/posts", test_webhook: false)
+ it "matches by webhook_id prefix and captures path params" do
+ workflow
+ result =
+ described_class.find(method: "GET", path: "abcd-1234/users/42/posts", test_webhook: false)
- expect(result[:webhook].webhook_id).to eq("abcd-1234")
- expect(result[:path_params]).to eq("id" => "42")
+ expect(result[:webhook].webhook_id).to eq("abcd-1234")
+ expect(result[:path_params]).to eq("id" => "42")
+ end
end
it "prefers the longest template when several share the same webhook_id" do
@@ -88,7 +98,7 @@ RSpec.describe DiscourseWorkflows::ActiveWebhooks do
end
it "is invalidated when webhook rows change" do
- make_workflow(path: "hooks/before", http_method: "POST")
+ activate_workflow(path: "hooks/before", http_method: "POST")
expect(
described_class.find(method: "POST", path: "hooks/before", test_webhook: false),
).to be_present
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb
index 0d609d98f57..d5edd4d0dd7 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb
@@ -22,19 +22,20 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowAiAgentCatalog do
)
end
- def invoke_tool(query:, include_disabled: false)
- context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ subject(:result) do
described_class.new(
{ query: query, include_disabled: include_disabled },
bot_user: Discourse.system_user,
llm: nil,
- context: context,
+ context: bot_context,
).invoke
end
- it "returns enabled AI agents matching the query", :aggregate_failures do
- result = invoke_tool(query: "support triage")
+ let(:query) { "support triage" }
+ let(:include_disabled) { false }
+ let(:bot_context) { DiscourseAi::Agents::BotContext.new(messages: [], user: admin) }
+ it "returns enabled AI agents matching the query", :aggregate_failures do
expect(result[:status]).to eq("success")
expect(result[:agents]).to contain_exactly(
include(
@@ -47,11 +48,14 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowAiAgentCatalog do
)
end
- it "can include disabled matches for awareness", :aggregate_failures do
- result = invoke_tool(query: "old", include_disabled: true)
+ context "when disabled agents are included" do
+ let(:query) { "old" }
+ let(:include_disabled) { true }
- expect(result[:agents]).to contain_exactly(
- include(id: disabled_agent.id, name: disabled_agent.name, enabled: false),
- )
+ it "returns disabled matches for awareness", :aggregate_failures do
+ expect(result[:agents]).to contain_exactly(
+ include(id: disabled_agent.id, name: disabled_agent.name, enabled: false),
+ )
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb
index 07ea3051e34..1a2934639fb 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb
@@ -3,24 +3,28 @@
RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
fab!(:admin)
- before { SiteSetting.discourse_ai_enabled = true }
+ subject(:result) { invoke_tool(query:, include_examples:) }
def invoke_tool(query: nil, include_examples: false)
- context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
described_class.new(
{ query: query, include_examples: include_examples }.compact,
bot_user: Discourse.system_user,
llm: nil,
- context: context,
+ context: bot_context,
).invoke
end
- def output_contract(nodes_by_type, type, output_index = 0)
- nodes_by_type.dig(type, :output_contracts, output_index)
- end
+ before { SiteSetting.discourse_ai_enabled = true }
- def output_fields(nodes_by_type, type, output_index = 0)
- output_contract(nodes_by_type, type, output_index).fetch(:fields)
+ let(:query) { nil }
+ let(:include_examples) { false }
+ let(:bot_context) { DiscourseAi::Agents::BotContext.new(messages: [], user: admin) }
+ let(:nodes_by_type) { result[:nodes].index_by { |node| node[:type] } }
+ let(:output_contracts_by_type) do
+ nodes_by_type.transform_values { |node| node.fetch(:output_contracts).first }.compact
+ end
+ let(:output_fields_by_type) do
+ output_contracts_by_type.transform_values { |contract| contract.fetch(:fields) }
end
it "finds the external chat integration action by provider keywords" do
@@ -50,11 +54,8 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
end
it "exposes post author, topic link, and action output fields", :aggregate_failures do
- result = invoke_tool
- nodes_by_type = result[:nodes].index_by { |node| node[:type] }
-
expect(result[:status]).to eq("success")
- expect(output_fields(nodes_by_type, "trigger:topic_created")).to include(
+ expect(output_fields_by_type.fetch("trigger:topic_created")).to include(
"post.user_id" => "integer",
"post.username" => "string",
"post.post_number" => "integer",
@@ -62,11 +63,11 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
"post.post_url" => "string",
"post.upload_ids" => "array<integer>",
)
- expect(output_fields(nodes_by_type, "trigger:topic_created")).not_to include(
+ expect(output_fields_by_type.fetch("trigger:topic_created")).not_to include(
"post.trust_level",
"user.trust_level",
)
- expect(output_fields(nodes_by_type, "trigger:post_created")).to include(
+ expect(output_fields_by_type.fetch("trigger:post_created")).to include(
"post.user_id" => "integer",
"post.username" => "string",
"post.post_number" => "integer",
@@ -80,19 +81,19 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
"user.moderator" => "boolean",
"user.staff" => "boolean",
)
- expect(output_fields(nodes_by_type, "trigger:post_created")).not_to include(
+ expect(output_fields_by_type.fetch("trigger:post_created")).not_to include(
"post.trust_level",
"post.admin",
"post.moderator",
"post.staff",
)
- expect(output_fields(nodes_by_type, "trigger:post_edited")).to include(
+ expect(output_fields_by_type.fetch("trigger:post_edited")).to include(
"post.id" => "integer",
"post.raw" => "string",
"user.trust_level" => "integer",
"user.trust_level_name" => "string",
)
- expect(output_fields(nodes_by_type, "trigger:topic_closed")).to include(
+ expect(output_fields_by_type.fetch("trigger:topic_closed")).to include(
"topic.id" => "integer",
"topic.title" => "string",
"topic.slug" => "string",
@@ -103,7 +104,7 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
"trigger:user_added_to_group" => "\"added\"",
"trigger:user_removed_from_group" => "\"removed\"",
}.each do |trigger_type, membership_action|
- expect(output_fields(nodes_by_type, trigger_type)).to include(
+ expect(output_fields_by_type.fetch(trigger_type)).to include(
"user.id" => "integer",
"user.username" => "string",
"user.trust_level" => "integer",
@@ -115,26 +116,26 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
"membership.automatic" => "boolean|null",
)
end
- expect(output_fields(nodes_by_type, "action:topic")).to include(
+ expect(output_fields_by_type.fetch("action:topic")).to include(
"topic.id" => "integer",
"topic.slug" => "string",
"topic.archived" => "boolean",
"post.post_url" => "string",
)
- expect(output_fields(nodes_by_type, "action:topic")).not_to include(
+ expect(output_fields_by_type.fetch("action:topic")).not_to include(
"post.trust_level",
"post.upload_ids",
)
- expect(output_fields(nodes_by_type, "action:topic_tags")).to include(
+ expect(output_fields_by_type.fetch("action:topic_tags")).to include(
"topic_id" => "integer",
"tag_names" => "array<string>",
)
- expect(output_fields(nodes_by_type, "action:post")).to include(
+ expect(output_fields_by_type.fetch("action:post")).to include(
"post.id" => "integer",
"post.topic_id" => "integer",
"post.post_url" => "string",
)
- expect(output_fields(nodes_by_type, "action:user")).to include(
+ expect(output_fields_by_type.fetch("action:user")).to include(
"user.id" => "integer",
"user.username" => "string",
"user.bio_raw" => "string|null",
@@ -145,13 +146,13 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
"user.groups" => "array<object>",
"user.groups[0].name" => "string",
)
- expect(output_fields(nodes_by_type, "action:send_personal_message")).to include(
+ expect(output_fields_by_type.fetch("action:send_personal_message")).to include(
"topic.id" => "integer",
"topic.slug" => "string",
"post.id" => "integer",
"post.post_url" => "string",
)
- expect(output_contract(nodes_by_type, "action:group")[:variants]).to include(
+ expect(output_contracts_by_type.fetch("action:group")[:variants]).to include(
a_hash_including(
mode: "replace",
display_options: {
@@ -185,7 +186,7 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
fields: a_hash_including("group_membership.in_group" => "boolean"),
),
)
- expect(output_contract(nodes_by_type, "flow:wait")[:variants]).to include(
+ expect(output_contracts_by_type.fetch("flow:wait")[:variants]).to include(
a_hash_including(
mode: "replace",
display_options: {
@@ -196,29 +197,34 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
fields: a_hash_including("method" => "string", "body" => "unknown"),
),
)
- expect(output_fields(nodes_by_type, "trigger:chat_message_created")).to include(
+ expect(output_fields_by_type.fetch("trigger:chat_message_created")).to include(
"message.id" => "integer",
"channel.id" => "integer",
"user.id" => "integer",
"user.username" => "string",
"user.avatar_template" => "string",
)
- expect(output_fields(nodes_by_type, "trigger:chat_message_created")).not_to include(
+ expect(output_fields_by_type.fetch("trigger:chat_message_created")).not_to include(
"user.trust_level",
"user.admin",
"user.moderator",
"user.staff",
)
- expect(output_fields(nodes_by_type, "action:ai_agent")).to include("result" => "string")
+ expect(output_fields_by_type.fetch("action:ai_agent")).to include("result" => "string")
end
it "matches broad multi-term catalog queries", :aggregate_failures do
result =
- invoke_tool(
- query:
- "trigger topic_closed action topic get condition filter chat message dm group membership user profile trust title",
- include_examples: true,
- )
+ described_class.new(
+ {
+ query:
+ "trigger topic_closed action topic get condition filter chat message dm group membership user profile trust title",
+ include_examples: true,
+ },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: bot_context,
+ ).invoke
node_types = result[:nodes].map { |node| node[:type] }
expect(node_types).to include(
@@ -236,7 +242,13 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
end
it "matches AI agent runner and attachment queries" do
- result = invoke_tool(query: "runner permissions attachments", include_examples: true)
+ result =
+ described_class.new(
+ { query: "runner permissions attachments", include_examples: true },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: bot_context,
+ ).invoke
ai_agent_node = result[:nodes].find { |node| node[:type] == "action:ai_agent" }
expect(ai_agent_node).to be_present
@@ -245,7 +257,13 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
end
it "includes declarative filter and topic lookup examples", :aggregate_failures do
- result = invoke_tool(include_examples: true)
+ result =
+ described_class.new(
+ { include_examples: true },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: bot_context,
+ ).invoke
filter_node = result[:nodes].find { |node| node[:type] == "condition:filter" }
group_node = result[:nodes].find { |node| node[:type] == "action:group" }
user_node = result[:nodes].find { |node| node[:type] == "action:user" }
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_script_context_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_script_context_spec.rb
index c161e855f55..b70f1906c72 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_script_context_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_script_context_spec.rb
@@ -21,19 +21,21 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowScriptContext do
)
end
+ subject(:result) { invoke_tool(upstream_node_id) }
+
def invoke_tool(upstream_node_id)
- context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
described_class.new(
{ workflow_id: workflow.id, upstream_node_id: upstream_node_id },
bot_user: Discourse.system_user,
llm: nil,
- context: context,
+ context: bot_context,
).invoke
end
- it "uses the node's declared fields before it has run" do
- result = invoke_tool("post-created")
+ let(:upstream_node_id) { "post-created" }
+ let(:bot_context) { DiscourseAi::Agents::BotContext.new(messages: [], user: admin) }
+ it "uses the node's declared fields before it has run" do
expect(result.dig(:upstream_fields, :output_fields, 0)).to include(
"post.id" => "integer",
"user.username" => "string",
@@ -45,8 +47,6 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowScriptContext do
node_name = workflow.nodes.find { |node| node["id"] == "post-created" }["name"]
workflow.update_node_pin_data!(node_name, [{ "json" => { "pinned_only" => true } }])
- result = invoke_tool("post-created")
-
expect(result.dig(:upstream_fields, :output_fields, 0)).to eq("pinned_only" => "boolean")
end
@@ -54,8 +54,6 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowScriptContext do
node_name = workflow.nodes.find { |node| node["id"] == "post-created" }["name"]
workflow.update_node_pin_data!(node_name, [{ "json" => {} }])
- result = invoke_tool("post-created")
-
expect(result.dig(:upstream_fields, :output_fields)).to eq([{}])
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb
index 199c5134c59..63b5815d46d 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb
@@ -71,10 +71,6 @@ RSpec.describe DiscourseWorkflows::DataTables::Facade do
)
end
- def build_row_input(data, fill_missing: false)
- facade.build_row_input(data: data, fill_missing: fill_missing)
- end
-
describe "#build_query" do
it "returns an invalid query when the filter is invalid" do
query =
@@ -496,14 +492,17 @@ RSpec.describe DiscourseWorkflows::DataTables::Facade do
describe "#insert" do
it "inserts a row with cast data" do
- row = facade.insert(build_row_input({ "email" => "[email protected]" }, fill_missing: true))
+ row =
+ facade.insert(
+ facade.build_row_input(data: { "email" => "[email protected]" }, fill_missing: true),
+ )
expect(row["email"]).to eq("[email protected]")
expect(row["score"]).to be_nil
end
it "inserts a default row when data is empty" do
- row = facade.insert(build_row_input({}))
+ row = facade.insert(facade.build_row_input(data: {}))
expect(row["id"]).to be_present
end
@@ -512,20 +511,26 @@ RSpec.describe DiscourseWorkflows::DataTables::Facade do
describe "#update_row" do
it "updates a single row and returns it" do
updated =
- facade.update_row(row_id: row_1["id"], row_input: build_row_input({ "score" => 99 }))
+ facade.update_row(
+ row_id: row_1["id"],
+ row_input: facade.build_row_input(data: { "score" => 99 }),
+ )
expect(updated["score"]).to eq(99)
expect(updated["email"]).to eq("[email protected]")
end
it "returns nil for a non-existent id" do
- updated = facade.update_row(row_id: -1, row_input: build_row_input({ "score" => 99 }))
+ updated =
+ facade.update_row(row_id: -1, row_input: facade.build_row_input(data: { "score" => 99 }))
expect(updated).to be_nil
end
it "returns nil when the row input is empty" do
- expect(facade.update_row(row_id: row_1["id"], row_input: build_row_input({}))).to be_nil
+ expect(
+ facade.update_row(row_id: row_1["id"], row_input: facade.build_row_input(data: {})),
+ ).to be_nil
end
end
@@ -542,7 +547,7 @@ RSpec.describe DiscourseWorkflows::DataTables::Facade do
],
},
),
- row_input: build_row_input({ "score" => 99 }),
+ row_input: facade.build_row_input(data: { "score" => 99 }),
)
expect(updated_count).to eq(1)
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb
index cfeb9dc8968..8ad05349da0 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb
@@ -1,9 +1,7 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::Executor::CodeRunner do
- let(:runtime_state) { DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new }
-
- def build_runner(items: [{ "json" => {} }], parameters: {}, resolver_context: {})
+ subject(:runner) do
described_class.new(
input_items: items,
parameters: parameters,
@@ -18,50 +16,53 @@ RSpec.describe DiscourseWorkflows::Executor::CodeRunner do
)
end
+ let(:runtime_state) { DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new }
+ let(:items) { [{ "json" => {} }] }
+ let(:parameters) { {} }
+ let(:resolver_context) { {} }
+
it "runs JavaScript in runCode mode" do
- result =
- build_runner.run({ "nodeMode" => "runCode", "code" => "return { json: { value: 2 } };" }, 0)
+ result = runner.run({ "nodeMode" => "runCode", "code" => "return { json: { value: 2 } };" }, 0)
expect(result).to eq("json" => { "value" => 2 })
end
- it "runs JavaScript once for all items with $input helpers" do
- items = [{ "json" => { "value" => 1 } }, { "json" => { "value" => 2 } }]
- result =
- build_runner(items: items).run(
- {
- "nodeMode" => "runOnceForAllItems",
- "code" => "return $input.all().map(function(item) { return item.json.value; });",
- },
- 0,
- )
+ context "with multiple input items" do
+ let(:items) { [{ "json" => { "value" => 1 } }, { "json" => { "value" => 2 } }] }
- expect(result).to eq([1, 2])
- end
+ it "runs JavaScript once for all items with $input helpers" do
+ result =
+ runner.run(
+ {
+ "nodeMode" => "runOnceForAllItems",
+ "code" => "return $input.all().map(function(item) { return item.json.value; });",
+ },
+ 0,
+ )
- it "runs JavaScript once for each item in the requested chunk" do
- items = [{ "json" => { "value" => 1 } }, { "json" => { "value" => 2 } }]
- result =
- build_runner(items: items).run(
- {
- "nodeMode" => "runOnceForEachItem",
- "code" => "return { json: { value: $json.value, index: $itemIndex } };",
- "chunk" => {
- "startIndex" => 1,
- "count" => 1,
+ expect(result).to eq([1, 2])
+ end
+
+ it "runs JavaScript once for each item in the requested chunk" do
+ result =
+ runner.run(
+ {
+ "nodeMode" => "runOnceForEachItem",
+ "code" => "return { json: { value: $json.value, index: $itemIndex } };",
+ "chunk" => {
+ "startIndex" => 1,
+ "count" => 1,
+ },
},
- },
- 0,
- )
+ 0,
+ )
- expect(result).to eq([{ "json" => { "value" => 2, "index" => 1 } }])
+ expect(result).to eq([{ "json" => { "value" => 2, "index" => 1 } }])
+ end
end
it "merges sandbox logs into the runtime state" do
- build_runner.run(
- { "nodeMode" => "runCode", "code" => 'console.log("from code"); return null;' },
- 0,
- )
+ runner.run({ "nodeMode" => "runCode", "code" => 'console.log("from code"); return null;' }, 0)
expect(runtime_state.log.entries).to contain_exactly(
include("level" => "info", "message" => "from code"),
@@ -70,7 +71,7 @@ RSpec.describe DiscourseWorkflows::Executor::CodeRunner do
it "rejects invalid JavaScript additional property names" do
expect {
- build_runner.run(
+ runner.run(
{
"nodeMode" => "runCode",
"code" => "return null;",
@@ -84,8 +85,6 @@ RSpec.describe DiscourseWorkflows::Executor::CodeRunner do
end
it "preserves JavaScript null and undefined as distinct Ruby values" do
- runner = build_runner
-
null_result = runner.run({ "nodeMode" => "runCode", "code" => "return null;" }, 0)
undefined_result = runner.run({ "nodeMode" => "runCode", "code" => "return;" }, 0)
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb
index 7a92af0804e..e498fa885ac 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb
@@ -1,189 +1,178 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::Executor::ParameterResolver do
- let(:runtime_state) { DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new }
+ subject(:resolver) do
+ described_class.new(
+ parameters: parameters,
+ property_schema: schema,
+ resolver: expression_resolver,
+ input_items: items,
+ runtime_state: runtime_state,
+ )
+ end
- def build_resolver(parameters, schema: {}, items: [{ "json" => {} }])
- resolver_context = { "$json" => items.first.fetch("json") { {} } }
- sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
- expression_resolver =
- DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
- parameter_resolver =
- described_class.new(
- parameters: parameters,
- property_schema: schema,
- resolver: expression_resolver,
- input_items: items,
- runtime_state: runtime_state,
- )
+ let(:runtime_state) { DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new }
+ let(:schema) { {} }
+ let(:items) { [{ "json" => {} }] }
+ let(:resolver_context) { { "$json" => items.first.fetch("json") { {} } } }
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new(resolver_context) }
+ let(:expression_resolver) do
+ DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ end
- [parameter_resolver, expression_resolver, sandbox]
+ after do
+ expression_resolver.dispose
+ sandbox.dispose
end
- it "resolves nested paths, defaults, and raw expressions" do
- resolver, expression_resolver, sandbox =
- build_resolver(
- { "outer" => { "inner" => "={{ $json.value }}" }, "count" => "={{ $json.count }}" },
- items: [{ "json" => { "value" => "resolved", "count" => "4" } }],
- )
+ context "with nested parameters" do
+ let(:parameters) do
+ { "outer" => { "inner" => "={{ $json.value }}" }, "count" => "={{ $json.count }}" }
+ end
+ let(:items) { [{ "json" => { "value" => "resolved", "count" => "4" } }] }
- expect(resolver.resolve("outer.inner", 0)).to eq("resolved")
- expect(resolver.resolve("outer.missing", 0, default: "fallback")).to eq("fallback")
- expect(resolver.resolve("outer.inner", 0, options: { raw_expressions: true })).to eq(
- "={{ $json.value }}",
- )
- ensure
- expression_resolver&.dispose
- sandbox&.dispose
+ it "resolves paths, defaults, and raw expressions" do
+ expect(resolver.resolve("outer.inner", 0)).to eq("resolved")
+ expect(resolver.resolve("outer.missing", 0, default: "fallback")).to eq("fallback")
+ expect(resolver.resolve("outer.inner", 0, options: { raw_expressions: true })).to eq(
+ "={{ $json.value }}",
+ )
+ end
end
- it "keeps no_data_expression values literal" do
- resolver, expression_resolver, sandbox =
- build_resolver(
- { "code" => "={{ $json.value }}" },
- schema: {
- code: {
- type: :string,
- no_data_expression: true,
- },
- },
- items: [{ "json" => { "value" => "resolved" } }],
- )
+ context "with a no_data_expression field" do
+ let(:parameters) { { "code" => "={{ $json.value }}" } }
+ let(:schema) { { code: { type: :string, no_data_expression: true } } }
+ let(:items) { [{ "json" => { "value" => "resolved" } }] }
- expect(resolver.resolve("code", 0)).to eq("={{ $json.value }}")
- ensure
- expression_resolver&.dispose
- sandbox&.dispose
+ it "keeps its value literal" do
+ expect(resolver.resolve("code", 0)).to eq("={{ $json.value }}")
+ end
end
- it "resolves condition-builder parameters and records condition metadata" do
- resolver, expression_resolver, sandbox =
- build_resolver(
- {
- "conditions" => [
- {
- "leftValue" => "={{ $json.status }}",
- "operator" => {
- "type" => "string",
- "operation" => "equals",
- },
- "rightValue" => "open",
- },
- ],
- },
- schema: {
- conditions: {
- ui: {
- control: :condition_builder,
+ context "with condition-builder parameters" do
+ let(:parameters) do
+ {
+ "conditions" => [
+ {
+ "leftValue" => "={{ $json.status }}",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
},
+ "rightValue" => "open",
},
- },
- items: [{ "json" => { "status" => "open" } }],
- )
+ ],
+ }
+ end
+ let(:schema) { { conditions: { ui: { control: :condition_builder } } } }
+ let(:items) { [{ "json" => { "status" => "open" } }] }
- expect(resolver.resolve(:conditions, 0)).to eq(true)
- expect(runtime_state.step_metadata["conditions"]).to contain_exactly(
- include("left" => "open", "right" => "open", "passed" => true),
- )
- ensure
- expression_resolver&.dispose
- sandbox&.dispose
+ it "resolves them and records condition metadata" do
+ expect(resolver.resolve(:conditions, 0)).to eq(true)
+ expect(runtime_state.step_metadata["conditions"]).to contain_exactly(
+ include("left" => "open", "right" => "open", "passed" => true),
+ )
+ end
end
- it "resolves fixed collection rows with their nested schemas" do
- resolver, expression_resolver, sandbox =
- build_resolver(
- {
- "fields" => {
- "values" => [{ "name" => "={{ $json.name }}", "literal" => "={{ $json.name }}" }],
- },
+ context "with fixed collection rows" do
+ let(:parameters) do
+ {
+ "fields" => {
+ "values" => [{ "name" => "={{ $json.name }}", "literal" => "={{ $json.name }}" }],
},
- schema: {
- fields: {
- type: :fixed_collection,
- options: [
- {
- name: "values",
- values: {
- name: {
- type: :string,
- },
- literal: {
- type: :string,
- no_data_expression: true,
- },
+ }
+ end
+ let(:schema) do
+ {
+ fields: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ name: {
+ type: :string,
+ },
+ literal: {
+ type: :string,
+ no_data_expression: true,
},
},
- ],
- },
+ },
+ ],
},
- items: [{ "json" => { "name" => "Ada" } }],
- )
+ }
+ end
+ let(:items) { [{ "json" => { "name" => "Ada" } }] }
- expect(resolver.resolve("fields.values", 0)).to eq(
- [{ "name" => "Ada", "literal" => "={{ $json.name }}" }],
- )
- ensure
- expression_resolver&.dispose
- sandbox&.dispose
+ it "resolves rows with their nested schemas" do
+ expect(resolver.resolve("fields.values", 0)).to eq(
+ [{ "name" => "Ada", "literal" => "={{ $json.name }}" }],
+ )
+ end
end
- it "resolves collection option values with their option schemas" do
- resolver, expression_resolver, sandbox =
- build_resolver(
- { "updates" => { "title" => "={{ $json.title }}", "trust_level_locked" => "false" } },
- schema: {
- updates: {
- type: :collection,
- options: [
- { name: "title", type: :string },
- { name: "trust_level_locked", type: :boolean },
- ],
- },
+ context "with collection option values" do
+ let(:parameters) do
+ { "updates" => { "title" => "={{ $json.title }}", "trust_level_locked" => "false" } }
+ end
+ let(:schema) do
+ {
+ updates: {
+ type: :collection,
+ options: [
+ { name: "title", type: :string },
+ { name: "trust_level_locked", type: :boolean },
+ ],
},
- items: [{ "json" => { "title" => "Member" } }],
- )
+ }
+ end
+ let(:items) { [{ "json" => { "title" => "Member" } }] }
- expect(resolver.resolve("updates", 0)).to eq("title" => "Member", "trust_level_locked" => false)
- ensure
- expression_resolver&.dispose
- sandbox&.dispose
+ it "resolves them with their option schemas" do
+ expect(resolver.resolve("updates", 0)).to eq(
+ "title" => "Member",
+ "trust_level_locked" => false,
+ )
+ end
end
- it "coerces boolean values using the property schema" do
- resolver, expression_resolver, sandbox =
- build_resolver(
- {
- "enabled" => "={{ $json.enabled }}",
- "disabled" => "false",
- "nested" => {
- "enabled" => "1",
- },
+ context "with boolean fields" do
+ let(:parameters) do
+ {
+ "enabled" => "={{ $json.enabled }}",
+ "disabled" => "false",
+ "nested" => {
+ "enabled" => "1",
},
- schema: {
- enabled: {
- type: :boolean,
- },
- disabled: {
- type: :boolean,
- },
- nested: {
- type: :object,
- fields: {
- enabled: {
- type: :boolean,
- },
+ }
+ end
+ let(:schema) do
+ {
+ enabled: {
+ type: :boolean,
+ },
+ disabled: {
+ type: :boolean,
+ },
+ nested: {
+ type: :object,
+ fields: {
+ enabled: {
+ type: :boolean,
},
},
},
- items: [{ "json" => { "enabled" => "true" } }],
- )
+ }
+ end
+ let(:items) { [{ "json" => { "enabled" => "true" } }] }
- expect(resolver.resolve("enabled", 0)).to eq(true)
- expect(resolver.resolve("disabled", 0)).to eq(false)
- expect(resolver.resolve("nested.enabled", 0)).to eq(true)
- ensure
- expression_resolver&.dispose
- sandbox&.dispose
+ it "coerces values using the property schema" do
+ expect(resolver.resolve("enabled", 0)).to eq(true)
+ expect(resolver.resolve("disabled", 0)).to eq(false)
+ expect(resolver.resolve("nested.enabled", 0)).to eq(true)
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb
index 01e9a2213ff..44a1cfddc4b 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb
@@ -1,11 +1,10 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::NodeIssues do
- def node_type_class(schema)
- Class.new { define_singleton_method(:property_schema) { schema } }
- end
+ subject(:issues) { described_class.for_node(node, node_type) }
- def node(configuration)
+ let(:configuration) { {} }
+ let(:node) do
DiscourseWorkflows::WorkflowSnapshot::SnapshotNode.new(
id: "n1",
type: "action:test",
@@ -14,114 +13,152 @@ RSpec.describe DiscourseWorkflows::NodeIssues do
parameters: configuration,
)
end
+ let(:node_type) do
+ Class
+ .new do
+ def initialize(schema)
+ @schema = schema
+ end
- it "returns no issues when all required fields are set" do
- schema = { form_title: { type: :string, required: true } }
- issues = described_class.for_node(node("form_title" => "My form"), node_type_class(schema))
- expect(issues).to be_empty
+ def property_schema
+ @schema
+ end
+ end
+ .new(schema)
end
- it "reports a top-level required field as missing" do
- schema = { form_title: { type: :string, required: true } }
- issues = described_class.for_node(node({}), node_type_class(schema))
- expect(issues).to eq([{ path: "form_title", name: "form_title", message: "required" }])
+ context "when all required fields are set" do
+ let(:schema) { { form_title: { type: :string, required: true } } }
+ let(:configuration) { { "form_title" => "My form" } }
+
+ it { is_expected.to be_empty }
end
- it "treats blank strings as missing" do
- schema = { form_title: { type: :string, required: true } }
- issues = described_class.for_node(node("form_title" => " "), node_type_class(schema))
- expect(issues.size).to eq(1)
+ context "when a top-level required field is missing" do
+ let(:schema) { { form_title: { type: :string, required: true } } }
+
+ it "reports the field" do
+ expect(issues).to eq([{ path: "form_title", name: "form_title", message: "required" }])
+ end
end
- it "walks fixed collection items and reports missing nested required fields" do
- schema = {
- form_fields: {
- type: :fixed_collection,
- options: [
- {
- name: "values",
- values: {
- field_label: {
- type: :string,
- required: true,
- },
- field_type: {
- type: :options,
- required: true,
+ context "when a required string is blank" do
+ let(:schema) { { form_title: { type: :string, required: true } } }
+ let(:configuration) { { "form_title" => " " } }
+
+ it "reports the field" do
+ expect(issues.size).to eq(1)
+ end
+ end
+
+ context "with missing required fields in fixed collection items" do
+ let(:schema) do
+ {
+ form_fields: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ field_label: {
+ type: :string,
+ required: true,
+ },
+ field_type: {
+ type: :options,
+ required: true,
+ },
},
},
- },
- ],
- },
- }
- config = {
- "form_fields" => {
- "values" => [
- { "field_label" => "", "field_type" => "text" },
- { "field_label" => "Name", "field_type" => "" },
- ],
- },
- }
-
- paths = described_class.for_node(node(config), node_type_class(schema)).map { |i| i[:path] }
- expect(paths).to contain_exactly(
- "form_fields.values.0.field_label",
- "form_fields.values.1.field_type",
- )
+ ],
+ },
+ }
+ end
+ let(:configuration) do
+ {
+ "form_fields" => {
+ "values" => [
+ { "field_label" => "", "field_type" => "text" },
+ { "field_label" => "Name", "field_type" => "" },
+ ],
+ },
+ }
+ end
+
+ it "reports each nested path" do
+ expect(issues.pluck(:path)).to contain_exactly(
+ "form_fields.values.0.field_label",
+ "form_fields.values.1.field_type",
+ )
+ end
end
- it "respects display_options show rules — hidden required fields are not reported" do
- schema = {
- page_type: {
- type: :options,
- },
- completion_title: {
- type: :string,
- required: true,
- display_options: {
- show: {
- page_type: %w[completion],
+ context "with display rules on a required field" do
+ let(:schema) do
+ {
+ page_type: {
+ type: :options,
+ },
+ completion_title: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ },
},
},
- },
- }
+ }
+ end
+
+ context "when the field is hidden" do
+ let(:configuration) { { "page_type" => "page" } }
+
+ it { is_expected.to be_empty }
+ end
- expect(
- described_class.for_node(node("page_type" => "page"), node_type_class(schema)),
- ).to be_empty
+ context "when the field is shown" do
+ let(:configuration) { { "page_type" => "completion" } }
- issues = described_class.for_node(node("page_type" => "completion"), node_type_class(schema))
- expect(issues.size).to eq(1)
+ it "reports the field" do
+ expect(issues.size).to eq(1)
+ end
+ end
end
- it "applies field defaults before checking required" do
- schema = { operation: { type: :options, required: true, default: "add" } }
- expect(described_class.for_node(node({}), node_type_class(schema))).to be_empty
+ context "when a required field has a default" do
+ let(:schema) { { operation: { type: :options, required: true, default: "add" } } }
+
+ it { is_expected.to be_empty }
end
- it "walks optional fields inside fixed collections" do
- schema = {
- form_fields: {
- type: :fixed_collection,
- options: [
- {
- name: "values",
- values: {
- field_label: {
- type: :string,
- required: true,
- },
- custom_required: {
- type: :string,
- required: true,
+ context "with a missing optional field inside a fixed collection" do
+ let(:schema) do
+ {
+ form_fields: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ field_label: {
+ type: :string,
+ required: true,
+ },
+ custom_required: {
+ type: :string,
+ required: true,
+ },
},
},
- },
- ],
- },
- }
- config = { "form_fields" => { "values" => [{ "field_label" => "Name" }] } }
- paths = described_class.for_node(node(config), node_type_class(schema)).map { |i| i[:path] }
- expect(paths).to eq(["form_fields.values.0.custom_required"])
+ ],
+ },
+ }
+ end
+ let(:configuration) { { "form_fields" => { "values" => [{ "field_label" => "Name" }] } } }
+
+ it "reports the nested field" do
+ expect(issues.pluck(:path)).to eq(["form_fields.values.0.custom_required"])
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_granted_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_granted_spec.rb
index 5111e046fb4..97333883fdf 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_granted_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_granted_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe DiscourseWorkflows::Nodes::BadgeGranted::V1 do
fab!(:other_badge) { Fabricate(:badge, name: "Other badge") }
describe ".load_options_context" do
- def load_options(filter: nil)
+ subject(:options) do
context =
DiscourseWorkflows::LoadOptionsContext.new(
method_name: "badges",
@@ -17,8 +17,10 @@ RSpec.describe DiscourseWorkflows::Nodes::BadgeGranted::V1 do
described_class.load_options_context(context)
end
+ let(:filter) { nil }
+
it "returns enabled badges for the chooser" do
- expect(load_options).to include(
+ expect(options).to include(
{ id: badge.id, name: badge.name },
{ id: other_badge.id, name: other_badge.name },
)
@@ -27,13 +29,15 @@ RSpec.describe DiscourseWorkflows::Nodes::BadgeGranted::V1 do
it "excludes disabled badges" do
disabled_badge = Fabricate(:badge, name: "Disabled badge", enabled: false)
- expect(load_options).not_to include({ id: disabled_badge.id, name: disabled_badge.name })
+ expect(options).not_to include({ id: disabled_badge.id, name: disabled_badge.name })
end
- it "filters badges by the filter term" do
- expect(load_options(filter: "Other badge")).to contain_exactly(
- { id: other_badge.id, name: other_badge.name },
- )
+ context "with a filter term" do
+ let(:filter) { "Other badge" }
+
+ it "filters badges" do
+ expect(options).to contain_exactly({ id: other_badge.id, name: other_badge.name })
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb
index 97d3a3c0538..bd7b01c3444 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Badge::V1 do
describe ".load_options_context" do
fab!(:badge_2) { Fabricate(:badge, name: "A badge") }
- def load_options(filter: nil)
+ subject(:options) do
context =
DiscourseWorkflows::LoadOptionsContext.new(
method_name: "badges",
@@ -18,8 +18,10 @@ RSpec.describe DiscourseWorkflows::Nodes::Badge::V1 do
described_class.load_options_context(context)
end
+ let(:filter) { nil }
+
it "returns enabled badges for the chooser" do
- expect(load_options).to include(
+ expect(options).to include(
{ id: badge_2.id, name: badge_2.name },
{ id: badge.id, name: badge.name },
)
@@ -27,13 +29,15 @@ RSpec.describe DiscourseWorkflows::Nodes::Badge::V1 do
it "excludes disabled badges" do
disabled_badge = Fabricate(:badge, name: "Disabled Badge", enabled: false)
- expect(load_options).not_to include({ id: disabled_badge.id, name: disabled_badge.name })
+ expect(options).not_to include({ id: disabled_badge.id, name: disabled_badge.name })
end
- it "filters badges by the filter term" do
- expect(load_options(filter: "A badge")).to contain_exactly(
- { id: badge_2.id, name: badge_2.name },
- )
+ context "with a filter term" do
+ let(:filter) { "A badge" }
+
+ it "filters badges" do
+ expect(options).to contain_exactly({ id: badge_2.id, name: badge_2.name })
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
index 7e71e7e82b6..65d4d098c42 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
@@ -35,7 +35,7 @@ RSpec.describe DiscourseWorkflows::Nodes::DataTable::V1 do
end
describe ".load_options_context" do
- def load_options(filter: nil)
+ subject(:options) do
context =
DiscourseWorkflows::LoadOptionsContext.new(
method_name: "data_tables",
@@ -46,21 +46,24 @@ RSpec.describe DiscourseWorkflows::Nodes::DataTable::V1 do
described_class.load_options_context(context)
end
+ let(:filter) { nil }
+
it "marks reserved columns" do
- tables = load_options
- table_meta = tables.find { |dt| dt[:id] == data_table.id }
+ table_meta = options.find { |dt| dt[:id] == data_table.id }
column_names_reserved = table_meta[:columns].select { |c| c[:reserved] }.map { |c| c[:name] }
expect(column_names_reserved).to contain_exactly("id", "created_at", "updated_at")
expect(table_meta[:columns].find { |c| c[:name] == "email" }).not_to have_key(:reserved)
end
- it "filters data tables by the filter term" do
- Fabricate(:discourse_workflows_data_table, name: "projects")
+ context "with a filter term" do
+ let(:filter) { "cont" }
- expect(load_options(filter: "cont").map { |table| table[:id] }).to contain_exactly(
- data_table.id,
- )
+ it "filters data tables" do
+ Fabricate(:discourse_workflows_data_table, name: "projects")
+
+ expect(options.map { |table| table[:id] }).to contain_exactly(data_table.id)
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
index 3f424e23a6f..3eac2465d67 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
@@ -1,10 +1,10 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::Nodes::Form::V1 do
- let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
- after { sandbox.dispose }
+ subject(:result) { described_class.new(parameters: configuration).execute(execution_context) }
- def build_exec_ctx(configuration, resume_token: nil)
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ let(:execution_context) do
DiscourseWorkflows::Executor::NodeExecutionContext.new(
input_items: [{ "json" => {} }],
parameters: configuration,
@@ -12,35 +12,39 @@ RSpec.describe DiscourseWorkflows::Nodes::Form::V1 do
node_context: {
},
resolver: DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox),
- resume_token: resume_token,
+ resume_token: "tok-xyz",
)
end
- describe "#execute" do
- it "returns input items for non-completion forms" do
- config = {
- "form_title" => "Approval",
- "form_description" => "Please approve",
- "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
- }
- exec_ctx = build_exec_ctx(config, resume_token: "tok-xyz")
-
- result = described_class.new(parameters: config).execute(exec_ctx)
+ after { sandbox.dispose }
- expect(result).to eq([exec_ctx.input_items])
+ describe "#execute" do
+ context "with a non-completion form" do
+ let(:configuration) do
+ {
+ "form_title" => "Approval",
+ "form_description" => "Please approve",
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ }
+ end
+
+ it "returns input items" do
+ expect(result).to eq([execution_context.input_items])
+ end
end
- it "passes completion forms through without reaching into flow context" do
- config = {
- "page_type" => "completion",
- "on_submission" => "completion_screen",
- "completion_title" => "Done",
- }
- exec_ctx = build_exec_ctx(config, resume_token: "tok-xyz")
-
- result = described_class.new(parameters: config).execute(exec_ctx)
-
- expect(result).to eq([exec_ctx.input_items])
+ context "with a completion form" do
+ let(:configuration) do
+ {
+ "page_type" => "completion",
+ "on_submission" => "completion_screen",
+ "completion_title" => "Done",
+ }
+ end
+
+ it "passes through without reaching into flow context" do
+ expect(result).to eq([execution_context.input_items])
+ end
end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
index edd1cd11040..0dc19f9aa3f 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Group::V1 do
fab!(:group_2) { Fabricate(:group, name: "another_group") }
describe ".load_options_context" do
- def load_options(parameters: {}, filter: nil)
+ subject(:options) do
context =
DiscourseWorkflows::LoadOptionsContext.new(
method_name: "groups",
@@ -19,9 +19,10 @@ RSpec.describe DiscourseWorkflows::Nodes::Group::V1 do
described_class.load_options_context(context)
end
- it "returns groups for the chooser", :aggregate_failures do
- options = load_options
+ let(:parameters) { {} }
+ let(:filter) { nil }
+ it "returns groups for the chooser", :aggregate_failures do
expect(options).to include(
{ id: group.id, name: group.name },
{ id: group_2.id, name: group_2.name },
@@ -31,10 +32,12 @@ RSpec.describe DiscourseWorkflows::Nodes::Group::V1 do
expect(option_ids).to include(*Group::AUTO_GROUPS.values)
end
- it "filters groups by the filter term" do
- expect(load_options(filter: "another")).to contain_exactly(
- { id: group_2.id, name: group_2.name },
- )
+ context "with a filter term" do
+ let(:filter) { "another" }
+
+ it "filters groups" do
+ expect(options).to contain_exactly({ id: group_2.id, name: group_2.name })
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb
index 3ea28bb235d..fcc32e418f1 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb
@@ -1,79 +1,93 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::Nodes::Limit::V1 do
- def execute(input_items, configuration = {})
- config = { "max_items" => 10, "keep" => "first" }.merge(configuration)
- execute_node_output(configuration: config, input_items: input_items).first
+ subject(:result) do
+ execute_node_output(configuration: configuration, input_items: input_items).first
end
- def make_indexed_items(count)
- Array.new(count) { |i| { "json" => { "index" => i } } }
- end
+ let(:item_count) { 5 }
+ let(:input_items) { Array.new(item_count) { |index| { "json" => { "index" => index } } } }
+ let(:max_items) { 10 }
+ let(:keep) { "first" }
+ let(:configuration) { { "max_items" => max_items, "keep" => keep } }
describe "#execute" do
- it "keeps the first N items by default" do
- result = execute(make_indexed_items(5), "max_items" => 3)
+ context "when keeping the first three items" do
+ let(:max_items) { 3 }
- expect(result.length).to eq(3)
- expect(result[0]["json"]["index"]).to eq(0)
- expect(result[1]["json"]["index"]).to eq(1)
- expect(result[2]["json"]["index"]).to eq(2)
+ it "returns the first three items" do
+ expect(result.map { |item| item["json"]["index"] }).to eq([0, 1, 2])
+ end
end
- it "keeps the last N items when keep is last" do
- result = execute(make_indexed_items(5), "max_items" => 2, "keep" => "last")
+ context "when keeping the last two items" do
+ let(:max_items) { 2 }
+ let(:keep) { "last" }
- expect(result.length).to eq(2)
- expect(result[0]["json"]["index"]).to eq(3)
- expect(result[1]["json"]["index"]).to eq(4)
+ it "returns the last two items" do
+ expect(result.map { |item| item["json"]["index"] }).to eq([3, 4])
+ end
end
- it "returns all items when max_items exceeds input size" do
- result = execute(make_indexed_items(3), "max_items" => 10)
+ context "when the limit exceeds the input size" do
+ let(:item_count) { 3 }
- expect(result.length).to eq(3)
+ it "returns all items" do
+ expect(result.length).to eq(3)
+ end
end
- it "returns empty array when input is empty" do
- result = execute([], "max_items" => 5)
+ context "without input items" do
+ let(:input_items) { [] }
+ let(:max_items) { 5 }
- expect(result).to eq([])
+ it { is_expected.to eq([]) }
end
- it "defaults to 10 items" do
- result = execute(make_indexed_items(15))
+ context "without an explicit limit" do
+ let(:item_count) { 15 }
+ let(:configuration) { {} }
- expect(result.length).to eq(10)
+ it "defaults to ten items" do
+ expect(result.length).to eq(10)
+ end
end
- it "handles max_items of 1" do
- result = execute(make_indexed_items(5), "max_items" => 1)
+ context "with a limit of one" do
+ let(:max_items) { 1 }
- expect(result.length).to eq(1)
- expect(result[0]["json"]["index"]).to eq(0)
+ it "returns the first item" do
+ expect(result.map { |item| item["json"]["index"] }).to eq([0])
+ end
end
- it "clamps max_items below 1 to 1" do
- result = execute(make_indexed_items(5), "max_items" => 0)
+ context "with a limit below one" do
+ let(:max_items) { 0 }
- expect(result.length).to eq(1)
- expect(result[0]["json"]["index"]).to eq(0)
+ it "clamps the limit to one" do
+ expect(result.map { |item| item["json"]["index"] }).to eq([0])
+ end
end
- it "handles max_items of 1 with keep last" do
- result = execute(make_indexed_items(5), "max_items" => 1, "keep" => "last")
+ context "when keeping the last item" do
+ let(:max_items) { 1 }
+ let(:keep) { "last" }
- expect(result.length).to eq(1)
- expect(result[0]["json"]["index"]).to eq(4)
+ it "returns the last item" do
+ expect(result.map { |item| item["json"]["index"] }).to eq([4])
+ end
end
- it "resolves max_items expressions through the execution context" do
- items = make_indexed_items(5)
- items.first["json"]["limit"] = 2
-
- result = execute(items, "max_items" => "={{ $json.limit }}")
+ context "with an expression limit" do
+ let(:max_items) { "={{ $json.limit }}" }
+ let(:input_items) do
+ [{ "json" => { "index" => 0, "limit" => 2 } }] +
+ (1...item_count).map { |index| { "json" => { "index" => index } } }
+ end
- expect(result.map { |item| item["json"]["index"] }).to eq([0, 1])
+ it "resolves the expression through the execution context" do
+ expect(result.map { |item| item["json"]["index"] }).to eq([0, 1])
+ end
end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
index d4dfaef152a..f9c3491e1ff 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
@@ -20,32 +20,33 @@ RSpec.describe DiscourseWorkflows::Nodes::Modal::V1 do
}
end
- def build_exec_ctx(configuration, ctx_user: nil, execution_id: 7, resume_token: "tok-7")
+ let(:execution_configuration) { config }
+ let(:context_user) { user }
+ let(:execution_context) do
DiscourseWorkflows::Executor::NodeExecutionContext.new(
input_items: [{ "json" => {} }],
- parameters: configuration,
+ parameters: execution_configuration,
property_schema: described_class.property_schema,
node_context: {
},
resolver: DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox),
- user: ctx_user,
- execution_id: execution_id,
- resume_token: resume_token,
+ user: context_user,
+ execution_id: 7,
+ resume_token: "tok-7",
)
end
describe "#execute" do
it "publishes the modal to the triggering user and pauses the execution" do
- exec_ctx = build_exec_ctx(config, ctx_user: user)
- allow(exec_ctx).to receive(:put_execution_to_wait).and_call_original
+ allow(execution_context).to receive(:put_execution_to_wait).and_call_original
messages =
MessageBus.track_publish(described_class.user_channel(user.id)) do
- result = described_class.new(parameters: config).execute(exec_ctx)
- expect(result).to eq([exec_ctx.input_items])
+ result = described_class.new(parameters: config).execute(execution_context)
+ expect(result).to eq([execution_context.input_items])
end
- expect(exec_ctx).to have_received(:put_execution_to_wait).with(nil)
+ expect(execution_context).to have_received(:put_execution_to_wait).with(nil)
expect(messages.size).to eq(1)
message = messages.first
expect(message.user_ids).to eq([user.id])
@@ -67,67 +68,75 @@ RSpec.describe DiscourseWorkflows::Nodes::Modal::V1 do
)
end
- it "binds the target user into the action ids so another user's token differs" do
- configuration = config.merge("target_user" => other_user.username)
- exec_ctx = build_exec_ctx(configuration, ctx_user: user)
-
- messages =
- MessageBus.track_publish(described_class.user_channel(other_user.id)) do
- described_class.new(parameters: configuration).execute(exec_ctx)
- end
-
- action_id = messages.first.data[:buttons].first["action_id"]
- payload = DiscourseWorkflows::InteractiveResume.action_payload(action_id)
- expect(payload["target_user_id"]).to eq(other_user.id)
- expect(payload["target_user_id"]).not_to eq(user.id)
+ context "with a configured target user" do
+ let(:execution_configuration) { config.merge("target_user" => other_user.username) }
+
+ it "binds the target user into the action ids" do
+ messages =
+ MessageBus.track_publish(described_class.user_channel(other_user.id)) do
+ described_class.new(parameters: execution_configuration).execute(execution_context)
+ end
+
+ action_id = messages.first.data[:buttons].first["action_id"]
+ payload = DiscourseWorkflows::InteractiveResume.action_payload(action_id)
+ expect(payload["target_user_id"]).to eq(other_user.id)
+ expect(payload["target_user_id"]).not_to eq(user.id)
+ end
+
+ it "sends the modal to the target instead of the triggering user" do
+ messages =
+ MessageBus.track_publish(described_class.user_channel(other_user.id)) do
+ described_class.new(parameters: execution_configuration).execute(execution_context)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.user_ids).to eq([other_user.id])
+ end
end
- it "sends the modal to a configured target user instead of the triggering user" do
- configuration = config.merge("target_user" => other_user.username)
- exec_ctx = build_exec_ctx(configuration, ctx_user: user)
-
- messages =
- MessageBus.track_publish(described_class.user_channel(other_user.id)) do
- described_class.new(parameters: configuration).execute(exec_ctx)
- end
-
- expect(messages.size).to eq(1)
- expect(messages.first.user_ids).to eq([other_user.id])
+ context "without a target user" do
+ let(:context_user) { nil }
+
+ it "raises a node error" do
+ expect {
+ described_class.new(parameters: config).execute(execution_context)
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.modal.no_target_user"),
+ )
+ end
end
- it "raises when no target user can be resolved" do
- exec_ctx = build_exec_ctx(config, ctx_user: nil)
-
- expect { described_class.new(parameters: config).execute(exec_ctx) }.to raise_error(
- DiscourseWorkflows::NodeError,
- I18n.t("discourse_workflows.errors.modal.no_target_user"),
- )
+ context "with a missing configured target user" do
+ let(:execution_configuration) { config.merge("target_user" => "ghost") }
+
+ it "raises a node error" do
+ expect {
+ described_class.new(parameters: execution_configuration).execute(execution_context)
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.modal.user_not_found", username: "ghost"),
+ )
+ end
end
- it "raises when the configured target user does not exist" do
- configuration = config.merge("target_user" => "ghost")
- exec_ctx = build_exec_ctx(configuration, ctx_user: user)
+ context "without buttons" do
+ let(:execution_configuration) { config.merge("buttons" => { "values" => [] }) }
- expect { described_class.new(parameters: configuration).execute(exec_ctx) }.to raise_error(
- DiscourseWorkflows::NodeError,
- I18n.t("discourse_workflows.errors.modal.user_not_found", username: "ghost"),
- )
- end
+ it "shows an informational modal without waiting" do
+ allow(execution_context).to receive(:put_execution_to_wait)
- it "shows an informational modal without waiting when there are no buttons" do
- configuration = config.merge("buttons" => { "values" => [] })
- exec_ctx = build_exec_ctx(configuration, ctx_user: user)
- allow(exec_ctx).to receive(:put_execution_to_wait)
+ messages =
+ MessageBus.track_publish(described_class.user_channel(user.id)) do
+ result =
+ described_class.new(parameters: execution_configuration).execute(execution_context)
+ expect(result).to eq([execution_context.input_items])
+ end
- messages =
- MessageBus.track_publish(described_class.user_channel(user.id)) do
- result = described_class.new(parameters: configuration).execute(exec_ctx)
- expect(result).to eq([exec_ctx.input_items])
- end
-
- expect(exec_ctx).not_to have_received(:put_execution_to_wait)
- expect(messages.size).to eq(1)
- expect(messages.first.data[:buttons]).to eq([])
+ expect(execution_context).not_to have_received(:put_execution_to_wait)
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:buttons]).to eq([])
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb
index 35358b4385f..d12c5712bd9 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb
@@ -1,139 +1,167 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::Nodes::RespondToWebhook::V1 do
- def rows(*values)
- { "values" => values }
+ subject(:webhook_response) do
+ described_class.new(parameters: configuration).execute(execution_context)
+ webhook_context.response
end
- def execute_response_node(configuration:, item:)
- request =
- DiscourseWorkflows::WebhookRequest.new(
- method: "POST",
- path: "test",
- webhook_url: "http://test.localhost/workflows/webhooks/test",
- )
- webhook_context = DiscourseWorkflows::WebhookContext.new(request: request)
- node = described_class.new(parameters: configuration)
- sandbox = DiscourseWorkflows::JsSandbox.new({ "$json" => item["json"] })
- resolver =
- DiscourseWorkflows::ExpressionResolver.new({ "$json" => item["json"] }, sandbox: sandbox)
- exec_ctx =
- DiscourseWorkflows::Executor::NodeExecutionContext.new(
- input_items: [item],
- resolver: resolver,
- parameters: configuration,
- property_schema: described_class.property_schema,
- webhook_context: webhook_context,
- )
-
- node.execute(exec_ctx)
- webhook_context.response
- ensure
- resolver&.dispose
- sandbox&.dispose
+ let(:configuration) { {} }
+ let(:request) do
+ DiscourseWorkflows::WebhookRequest.new(
+ method: "POST",
+ path: "test",
+ webhook_url: "http://test.localhost/workflows/webhooks/test",
+ )
+ end
+ let(:webhook_context) { DiscourseWorkflows::WebhookContext.new(request: request) }
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => item["json"] }) }
+ let(:resolver) do
+ DiscourseWorkflows::ExpressionResolver.new({ "$json" => item["json"] }, sandbox: sandbox)
+ end
+ let(:execution_context) do
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [item],
+ resolver: resolver,
+ parameters: configuration,
+ property_schema: described_class.property_schema,
+ webhook_context: webhook_context,
+ )
+ end
+
+ after do
+ resolver.dispose
+ sandbox.dispose
end
describe "#execute" do
let(:item) { { "json" => { "user_id" => 42 } } }
- it "rejects redirects to domains not in the allow list" do
- config = { "response_type" => "redirect", "redirect_url" => "https://example.com/thanks" }
- response = execute_response_node(configuration: config, item: item)
+ context "with a redirect outside the allow list" do
+ let(:configuration) do
+ { "response_type" => "redirect", "redirect_url" => "https://example.com/thanks" }
+ end
- expect(response.status_code).to eq(400)
- expect(response.body).to eq(error: "invalid_redirect_url")
+ it "rejects the redirect" do
+ expect(webhook_response.status_code).to eq(400)
+ expect(webhook_response.body).to eq(error: "invalid_redirect_url")
+ end
end
- it "rejects protocol-relative redirect URLs" do
- config = {
- "response_type" => "redirect",
- "redirect_url" => "//example.com/thanks",
- "allowed_redirect_domains" => rows({ "domain" => "example.com" }),
- }
- response = execute_response_node(configuration: config, item: item)
-
- expect(response.status_code).to eq(400)
- expect(response.body).to eq(error: "invalid_redirect_url")
+ context "with a protocol-relative redirect URL" do
+ let(:configuration) do
+ {
+ "response_type" => "redirect",
+ "redirect_url" => "//example.com/thanks",
+ "allowed_redirect_domains" => {
+ "values" => [{ "domain" => "example.com" }],
+ },
+ }
+ end
+
+ it "rejects the redirect" do
+ expect(webhook_response.status_code).to eq(400)
+ expect(webhook_response.body).to eq(error: "invalid_redirect_url")
+ end
end
- it "returns normalized allowed redirect domains" do
- config = {
- "response_type" => "redirect",
- "redirect_url" => "https://example.com/thanks",
- "allowed_redirect_domains" =>
- rows(
- { "domain" => " Example.com " },
- { "domain" => "*.Example.org" },
- { "domain" => "" },
- ),
- }
- response = execute_response_node(configuration: config, item: item)
-
- expect(response.status_code).to eq(302)
- expect(response.headers["Location"]).to eq("https://example.com/thanks")
+ context "with normalized allowed redirect domains" do
+ let(:configuration) do
+ {
+ "response_type" => "redirect",
+ "redirect_url" => "https://example.com/thanks",
+ "allowed_redirect_domains" => {
+ "values" => [
+ { "domain" => " Example.com " },
+ { "domain" => "*.Example.org" },
+ { "domain" => "" },
+ ],
+ },
+ }
+ end
+
+ it "returns the redirect" do
+ expect(webhook_response.status_code).to eq(302)
+ expect(webhook_response.headers["Location"]).to eq("https://example.com/thanks")
+ end
end
- it "returns JSON response data" do
- config = {
- "response_type" => "json",
- "status_code" => "201",
- "response_body" => '{"created": true}',
- }
- response = execute_response_node(configuration: config, item: item)
-
- expect(response.status_code).to eq(201)
- expect(response.body).to eq("created" => true)
+ context "with JSON response data" do
+ let(:configuration) do
+ {
+ "response_type" => "json",
+ "status_code" => "201",
+ "response_body" => '{"created": true}',
+ }
+ end
+
+ it "returns the configured response" do
+ expect(webhook_response.status_code).to eq(201)
+ expect(webhook_response.body).to eq("created" => true)
+ end
end
- it "keeps JSON null distinct from no data" do
- config = { "response_type" => "json", "response_body" => "null" }
- response = execute_response_node(configuration: config, item: item)
+ context "with a JSON null response" do
+ let(:configuration) { { "response_type" => "json", "response_body" => "null" } }
- expect(response.body).to be_nil
- expect(response).not_to be_no_body
+ it "keeps null distinct from no data" do
+ expect(webhook_response.body).to be_nil
+ expect(webhook_response).not_to be_no_body
+ end
end
- it "returns text response data" do
- config = { "response_type" => "text", "status_code" => "200", "response_body" => "OK thanks" }
- response = execute_response_node(configuration: config, item: item)
+ context "with text response data" do
+ let(:configuration) do
+ { "response_type" => "text", "status_code" => "200", "response_body" => "OK thanks" }
+ end
- expect(response.status_code).to eq(200)
- expect(response.body).to eq("OK thanks")
- expect(response.headers["Content-Type"]).to eq("text/plain; charset=utf-8")
+ it "returns the configured response" do
+ expect(webhook_response.status_code).to eq(200)
+ expect(webhook_response.body).to eq("OK thanks")
+ expect(webhook_response.headers["Content-Type"]).to eq("text/plain; charset=utf-8")
+ end
end
- it "returns no data response" do
- config = { "response_type" => "no_data", "status_code" => "204" }
- response = execute_response_node(configuration: config, item: item)
+ context "with no response data" do
+ let(:configuration) { { "response_type" => "no_data", "status_code" => "204" } }
- expect(response.status_code).to eq(204)
- expect(response.body).to be_nil
- expect(response).to be_no_body
+ it "returns a no-body response" do
+ expect(webhook_response.status_code).to eq(204)
+ expect(webhook_response.body).to be_nil
+ expect(webhook_response).to be_no_body
+ end
end
- it "defaults status code to 200 for json" do
- config = { "response_type" => "json", "response_body" => "{}" }
- response = execute_response_node(configuration: config, item: item)
+ context "with JSON and no status code" do
+ let(:configuration) { { "response_type" => "json", "response_body" => "{}" } }
- expect(response.status_code).to eq(200)
+ it "defaults the status code to 200" do
+ expect(webhook_response.status_code).to eq(200)
+ end
end
- it "includes custom headers when provided" do
- config = {
- "response_type" => "json",
- "response_body" => "{}",
- "response_headers" => rows({ "key" => "X-Custom", "value" => "hello" }),
- }
- response = execute_response_node(configuration: config, item: item)
-
- expect(response.headers).to eq({ "X-Custom" => "hello" })
+ context "with custom headers" do
+ let(:configuration) do
+ {
+ "response_type" => "json",
+ "response_body" => "{}",
+ "response_headers" => {
+ "values" => [{ "key" => "X-Custom", "value" => "hello" }],
+ },
+ }
+ end
+
+ it "includes them" do
+ expect(webhook_response.headers).to eq({ "X-Custom" => "hello" })
+ end
end
- it "responds with the first incoming item" do
- config = { "response_type" => "first_incoming_item" }
- response = execute_response_node(configuration: config, item: item)
+ context "with the first incoming item response type" do
+ let(:configuration) { { "response_type" => "first_incoming_item" } }
- expect(response.body).to eq("user_id" => 42)
+ it "responds with the item" do
+ expect(webhook_response.body).to eq("user_id" => 42)
+ end
end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/template_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/template_spec.rb
index 55238b70b39..ec6e59bd747 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/template_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/template_spec.rb
@@ -9,186 +9,192 @@ RSpec.describe DiscourseWorkflows::Nodes::Template::V1 do
fab!(:execution) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
- def execute_template(
- template = nil,
- mode: nil,
- input_items: [{ "json" => {} }],
- vars: {},
- workflow: nil,
- execution_id: nil
- )
- parameters = template.nil? ? {} : { "template" => template }
- parameters["mode"] = mode if mode
- resolver_context = { "$json" => input_items.first&.dig("json") || {} }
- sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context, vars: vars)
- resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
- exec_ctx =
- DiscourseWorkflows::Executor::NodeExecutionContext.new(
- input_items: input_items,
- parameters: parameters,
- property_schema: described_class.property_schema,
- resolver: resolver,
- vars: vars,
- workflow: workflow,
- execution_id: execution_id,
- )
-
- described_class.new.execute(exec_ctx).first
- ensure
- resolver&.dispose
- sandbox&.dispose
+ subject(:template_result) { described_class.new.execute(execution_context).first }
+
+ let(:template) { nil }
+ let(:mode) { nil }
+ let(:template_parameters) { { "template" => template, "mode" => mode }.compact }
+ let(:execution_items) { [{ "json" => {} }] }
+ let(:template_vars) { {} }
+ let(:workflow_context) { nil }
+ let(:execution_id) { nil }
+ let(:resolver_context) { { "$json" => execution_items.first&.dig("json") || {} } }
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new(resolver_context, vars: template_vars) }
+ let(:resolver) { DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox) }
+ let(:execution_context) do
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: execution_items,
+ parameters: template_parameters,
+ property_schema: described_class.property_schema,
+ resolver: resolver,
+ vars: template_vars,
+ workflow: workflow_context,
+ execution_id: execution_id,
+ )
end
- describe "#execute" do
- it "renders a single output from all input items" do
- result =
- execute_template(
- "{% for item in items %}{{ item.name }} {% endfor %}",
- input_items: [{ "json" => { "name" => "Alice" } }, { "json" => { "name" => "Bob" } }],
- )
+ after do
+ resolver.dispose
+ sandbox.dispose
+ end
- expect(result.map { |item| item["json"] }).to eq([{ "template" => "Alice Bob " }])
+ describe "#execute" do
+ context "with multiple input items" do
+ let(:template) { "{% for item in items %}{{ item.name }} {% endfor %}" }
+ let(:execution_items) do
+ [{ "json" => { "name" => "Alice" } }, { "json" => { "name" => "Bob" } }]
+ end
+
+ it "renders a single output from all input items" do
+ expect(template_result.map { |item| item["json"] }).to eq([{ "template" => "Alice Bob " }])
+ end
+
+ it "links the output item to every source item" do
+ expect(template_result.first["pairedItem"]).to eq([{ "item" => 0 }, { "item" => 1 }])
+ end
end
- it "renders one output per input item in each-item mode" do
- SiteSetting.title = "Each Item Forum"
-
- result =
- execute_template(
- "{{ item.name }} {{ item.item_index }}/{{ items_count }} {{ site_settings.title }}",
- mode: "runOnceForEachItem",
- input_items: [
- { "json" => { "name" => "Alice", "item_index" => 99 } },
- { "json" => { "name" => "Bob", "items_count" => 99 } },
+ context "in each-item mode" do
+ let(:template) do
+ "{{ item.name }} {{ item.item_index }}/{{ items_count }} {{ site_settings.title }}"
+ end
+ let(:mode) { "runOnceForEachItem" }
+ let(:execution_items) do
+ [
+ { "json" => { "name" => "Alice", "item_index" => 99 } },
+ { "json" => { "name" => "Bob", "items_count" => 99 } },
+ ]
+ end
+
+ it "renders one output per input item" do
+ SiteSetting.title = "Each Item Forum"
+
+ expect(template_result.map { |item| item["json"] }).to eq(
+ [
+ { "template" => "Alice 1/2 Each Item Forum" },
+ { "template" => "Bob 2/2 Each Item Forum" },
],
)
-
- expect(result.map { |item| item["json"] }).to eq(
- [
- { "template" => "Alice 1/2 Each Item Forum" },
- { "template" => "Bob 2/2 Each Item Forum" },
- ],
- )
- expect(result.map { |item| item["pairedItem"] }).to eq([{ "item" => 0 }, { "item" => 1 }])
+ expect(template_result.map { |item| item["pairedItem"] }).to eq(
+ [{ "item" => 0 }, { "item" => 1 }],
+ )
+ end
end
- it "exposes workflow metadata and all input items" do
- input_items = [
- {
- "json" => {
- "name" => "Alice",
- "vars" => {
- "project" => "Ignored",
- },
- "item" => {
- "json" => {
- "name" => "Ignored",
+ context "with workflow metadata and variables" do
+ let(:template) do
+ "{% for item in items %}{{ item.name }} {% endfor %}" \
+ "count={{ items_count }} var={{ vars.project }} " \
+ "workflow={{ workflow.name }} execution={{ execution.id }} " \
+ "{% for item in items %}item={{ item.item.json.name }} index={{ item.item_index }} {% endfor %}"
+ end
+ let(:execution_items) do
+ [
+ {
+ "json" => {
+ "name" => "Alice",
+ "vars" => {
+ "project" => "Ignored",
+ },
+ "item" => {
+ "json" => {
+ "name" => "Ignored",
+ },
},
+ "item_index" => 99,
},
- "item_index" => 99,
},
- },
- { "json" => { "name" => "Bob" } },
- ]
-
- result =
- execute_template(
- "{% for item in items %}{{ item.name }} {% endfor %}" \
- "count={{ items_count }} var={{ vars.project }} " \
- "workflow={{ workflow.name }} execution={{ execution.id }} " \
- "{% for item in items %}item={{ item.item.json.name }} index={{ item.item_index }} {% endfor %}",
- input_items: input_items,
- vars: {
- "project" => "Workflows",
- },
- workflow: workflow,
- execution_id: execution.id,
+ { "json" => { "name" => "Bob" } },
+ ]
+ end
+ let(:template_vars) { { "project" => "Workflows" } }
+ let(:workflow_context) { workflow }
+ let(:execution_id) { execution.id }
+
+ it "exposes them with all input items" do
+ expect(template_result.first["json"]).to eq(
+ "template" =>
+ "Alice Bob count=2 var=Workflows workflow=Template workflow execution=#{execution.id} " \
+ "item=Alice index=1 item=Bob index=2 ",
)
-
- expect(result.first["json"]).to eq(
- "template" =>
- "Alice Bob count=2 var=Workflows workflow=Template workflow execution=#{execution.id} " \
- "item=Alice index=1 item=Bob index=2 ",
- )
+ end
end
- it "exposes site settings and filters private settings" do
- SiteSetting.title = "Liquid Forum"
+ context "with site settings" do
+ let(:template) do
+ "title={{ site_settings.title }} " \
+ "secret={{ site_settings.discourse_connect_secret }} " \
+ "hidden={{ site_settings.vapid_public_key }}"
+ end
- result =
- execute_template(
- "title={{ site_settings.title }} " \
- "secret={{ site_settings.discourse_connect_secret }} " \
- "hidden={{ site_settings.vapid_public_key }}",
- )
+ it "exposes public settings and filters private settings" do
+ SiteSetting.title = "Liquid Forum"
- expect(result.first["json"]).to eq(
- "template" => "title=Liquid Forum secret=[FILTERED] hidden=[FILTERED]",
- )
+ expect(template_result.first["json"]).to eq(
+ "template" => "title=Liquid Forum secret=[FILTERED] hidden=[FILTERED]",
+ )
+ end
end
- it "emits only the template field", :aggregate_failures do
- result =
- execute_template(
- "{% for item in items %}{{ item.name }}{% endfor %}",
- input_items: [{ "json" => { "name" => "Alice", "extra" => "ignored" } }],
- )
+ context "with extra fields in an input item" do
+ let(:template) { "{% for item in items %}{{ item.name }}{% endfor %}" }
+ let(:execution_items) { [{ "json" => { "name" => "Alice", "extra" => "ignored" } }] }
- expect(result.first["json"]).to eq("template" => "Alice")
- expect(result.first["json"]).to match_node_output_schema(described_class)
+ it "emits only the template field", :aggregate_failures do
+ expect(template_result.first["json"]).to eq("template" => "Alice")
+ expect(template_result.first["json"]).to match_node_output_schema(described_class)
+ end
end
- it "links the output item to every source item" do
- result =
- execute_template(
- "{% for item in items %}{{ item.name }}{% endfor %}",
- input_items: [{ "json" => { "name" => "Alice" } }, { "json" => { "name" => "Bob" } }],
- )
+ context "with missing variables" do
+ let(:template) { "Hello {{ missing }}" }
- expect(result.first["pairedItem"]).to eq([{ "item" => 0 }, { "item" => 1 }])
+ it "renders them as blank strings" do
+ expect(template_result.first["json"]).to eq("template" => "Hello ")
+ end
end
- it "renders missing variables as blank strings" do
- result = execute_template("Hello {{ missing }}")
+ context "with HTML in a value" do
+ let(:template) { "{% for item in items %}{{ item.value }}{% endfor %}" }
+ let(:execution_items) { [{ "json" => { "value" => "<b>bold</b>" } }] }
- expect(result.first["json"]).to eq("template" => "Hello ")
+ it "uses default Liquid output rules" do
+ expect(template_result.first["json"]).to eq("template" => "<b>bold</b>")
+ end
end
- it "uses default Liquid output rules" do
- result =
- execute_template(
- "{% for item in items %}{{ item.value }}{% endfor %}",
- input_items: [{ "json" => { "value" => "<b>bold</b>" } }],
- )
-
- expect(result.first["json"]).to eq("template" => "<b>bold</b>")
+ context "without a template" do
+ let(:execution_items) do
+ [{ "json" => { "name" => "Alice" } }, { "json" => { "name" => "Bob" } }]
+ end
+
+ it "defaults to one showing item loop syntax" do
+ expect(template_result.first["json"]).to eq("template" => <<~TEXT)
+ Items:
+ - 1: Alice
+ - 2: Bob
+ TEXT
+ end
end
- it "defaults to a template showing item loop syntax" do
- result =
- execute_template(
- input_items: [{ "json" => { "name" => "Alice" } }, { "json" => { "name" => "Bob" } }],
- )
+ context "with invalid Liquid syntax" do
+ let(:template) { "{% for item in items %}" }
- expect(result.first["json"]).to eq("template" => <<~TEXT)
- Items:
- - 1: Alice
- - 2: Bob
- TEXT
+ it "raises a node error" do
+ expect { template_result }.to raise_error(DiscourseWorkflows::NodeError, /Invalid template/)
+ end
end
- it "raises a node error for invalid Liquid syntax" do
- expect { execute_template("{% for item in items %}") }.to raise_error(
- DiscourseWorkflows::NodeError,
- /Invalid template/,
- )
- end
+ context "with an invalid mode" do
+ let(:template) { "Hello" }
+ let(:mode) { "invalid" }
- it "raises a node error for invalid mode" do
- expect { execute_template("Hello", mode: "invalid") }.to raise_error(
- DiscourseWorkflows::NodeError,
- /Invalid Template mode/,
- )
+ it "raises a node error" do
+ expect { template_result }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Invalid Template mode/,
+ )
+ end
end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
index a41265a814d..bc2de3ddd7f 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
@@ -14,15 +14,15 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
fab!(:topic_with_custom_fields) { Fabricate(:topic, category: category) }
fab!(:other_topic_with_custom_fields) { Fabricate(:topic, category: category) }
- def load_options(filter: nil)
- context =
- DiscourseWorkflows::LoadOptionsContext.new(
- method_name: "topic_custom_fields",
- filter: filter,
- node_class: described_class,
- )
-
- described_class.load_options_context(context)
+ subject(:options) { described_class.load_options_context(load_options_context) }
+
+ let(:filter) { nil }
+ let(:load_options_context) do
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "topic_custom_fields",
+ filter: filter,
+ node_class: described_class,
+ )
end
before do
@@ -34,16 +34,18 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
end
it "returns distinct topic custom field names for the chooser" do
- expect(load_options).to contain_exactly(
+ expect(options).to contain_exactly(
{ id: "other_key", name: "other_key" },
{ id: "workflow_key", name: "workflow_key" },
)
end
- it "filters topic custom field names by the filter term" do
- expect(load_options(filter: "workflow")).to contain_exactly(
- { id: "workflow_key", name: "workflow_key" },
- )
+ context "with a filter" do
+ let(:filter) { "workflow" }
+
+ it "filters topic custom field names by the filter term" do
+ expect(options).to contain_exactly({ id: "workflow_key", name: "workflow_key" })
+ end
end
it "limits topic custom field names returned to the chooser" do
@@ -55,7 +57,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
)
end
- expect(load_options.length).to eq(described_class::CUSTOM_FIELD_OPTIONS_LIMIT)
+ expect(options.length).to eq(described_class::CUSTOM_FIELD_OPTIONS_LIMIT)
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb
index 670bbe135d3..feb344e2620 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb
@@ -1,10 +1,11 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::Nodes::Wait::V1 do
- let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
- after { sandbox.dispose }
+ subject(:result) { described_class.new(parameters: configuration).execute(execution_context) }
- def build_exec_ctx(configuration, resume_token: nil)
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ let(:resume_token) { nil }
+ let(:execution_context) do
DiscourseWorkflows::Executor::NodeExecutionContext.new(
input_items: [{ "json" => {} }],
parameters: configuration,
@@ -16,6 +17,8 @@ RSpec.describe DiscourseWorkflows::Nodes::Wait::V1 do
)
end
+ after { sandbox.dispose }
+
describe ".capabilities" do
it "marks the node as not producing data" do
expect(described_class.capabilities).to include(produces_data: false)
@@ -23,56 +26,59 @@ RSpec.describe DiscourseWorkflows::Nodes::Wait::V1 do
end
describe "#execute" do
- it "returns input items for interval mode" do
- config = { "resume" => "time_interval", "wait_amount" => 2, "wait_unit" => "hours" }
- exec_ctx = build_exec_ctx(config)
-
- result = described_class.new(parameters: config).execute(exec_ctx)
-
- expect(result.first).to eq(exec_ctx.input_items)
+ context "with interval mode" do
+ let(:configuration) do
+ { "resume" => "time_interval", "wait_amount" => 2, "wait_unit" => "hours" }
+ end
+
+ it "returns input items" do
+ expect(result.first).to eq(execution_context.input_items)
+ end
end
- it "returns input items for webhook mode" do
- config = { "resume" => "webhook" }
- exec_ctx = build_exec_ctx(config, resume_token: "tok-abc")
-
- result = described_class.new(parameters: config).execute(exec_ctx)
+ context "with webhook mode" do
+ let(:configuration) { { "resume" => "webhook" } }
+ let(:resume_token) { "tok-abc" }
- expect(result.first).to eq(exec_ctx.input_items)
+ it "returns input items" do
+ expect(result.first).to eq(execution_context.input_items)
+ end
end
- it "returns input items for bounded webhook waits" do
- config = {
- "resume" => "webhook",
- "limit_wait_time" => true,
- "timeout_amount" => 3,
- "timeout_unit" => "hours",
- }
- exec_ctx = build_exec_ctx(config, resume_token: "tok-abc")
-
- result = described_class.new(parameters: config).execute(exec_ctx)
-
- expect(result.first).to eq(exec_ctx.input_items)
+ context "with a bounded webhook wait" do
+ let(:configuration) do
+ {
+ "resume" => "webhook",
+ "limit_wait_time" => true,
+ "timeout_amount" => 3,
+ "timeout_unit" => "hours",
+ }
+ end
+ let(:resume_token) { "tok-abc" }
+
+ it "returns input items" do
+ expect(result.first).to eq(execution_context.input_items)
+ end
end
- it "raises on a non-positive wait amount" do
- config = { "resume" => "time_interval", "wait_amount" => 0, "wait_unit" => "hours" }
- exec_ctx = build_exec_ctx(config)
+ context "with a non-positive wait amount" do
+ let(:configuration) do
+ { "resume" => "time_interval", "wait_amount" => 0, "wait_unit" => "hours" }
+ end
- expect { described_class.new(parameters: config).execute(exec_ctx) }.to raise_error(
- DiscourseWorkflows::NodeError,
- /Wait amount/,
- )
+ it "raises a node error" do
+ expect { result }.to raise_error(DiscourseWorkflows::NodeError, /Wait amount/)
+ end
end
- it "raises on an invalid wait unit" do
- config = { "resume" => "time_interval", "wait_amount" => 1, "wait_unit" => "weeks" }
- exec_ctx = build_exec_ctx(config)
+ context "with an invalid wait unit" do
+ let(:configuration) do
+ { "resume" => "time_interval", "wait_amount" => 1, "wait_unit" => "weeks" }
+ end
- expect { described_class.new(parameters: config).execute(exec_ctx) }.to raise_error(
- DiscourseWorkflows::NodeError,
- /Invalid wait unit/,
- )
+ it "raises a node error" do
+ expect { result }.to raise_error(DiscourseWorkflows::NodeError, /Invalid wait unit/)
+ end
end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/statistics_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/statistics_spec.rb
index 614209adc55..b7f8e6cca20 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/statistics_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/statistics_spec.rb
@@ -5,14 +5,6 @@ RSpec.describe DiscourseWorkflows::Statistics do
fab!(:user)
- def log_runs(workflow, date:, runs: 1)
- DiscourseWorkflows::ExecutionStat.create!(
- workflow_id: workflow.id,
- date: date,
- total_runs: runs,
- )
- end
-
describe ".total" do
it "counts every workflow" do
Fabricate(:discourse_workflows_workflow)
@@ -66,9 +58,21 @@ RSpec.describe DiscourseWorkflows::Statistics do
one = Fabricate(:discourse_workflows_workflow)
two = Fabricate(:discourse_workflows_workflow)
- log_runs(one, date: Date.current, runs: 3)
- log_runs(one, date: 10.days.ago.to_date, runs: 2)
- log_runs(two, date: 45.days.ago.to_date, runs: 5)
+ DiscourseWorkflows::ExecutionStat.create!(
+ workflow_id: one.id,
+ date: Date.current,
+ total_runs: 3,
+ )
+ DiscourseWorkflows::ExecutionStat.create!(
+ workflow_id: one.id,
+ date: 10.days.ago.to_date,
+ total_runs: 2,
+ )
+ DiscourseWorkflows::ExecutionStat.create!(
+ workflow_id: two.id,
+ date: 45.days.ago.to_date,
+ total_runs: 5,
+ )
expect(described_class.executed).to eq(
last_day: 1,
@@ -83,9 +87,21 @@ RSpec.describe DiscourseWorkflows::Statistics do
it "sums runs in each window plus a lifetime count" do
workflow = Fabricate(:discourse_workflows_workflow)
- log_runs(workflow, date: Date.current, runs: 3)
- log_runs(workflow, date: 10.days.ago.to_date, runs: 2)
- log_runs(workflow, date: 45.days.ago.to_date, runs: 5)
+ DiscourseWorkflows::ExecutionStat.create!(
+ workflow_id: workflow.id,
+ date: Date.current,
+ total_runs: 3,
+ )
+ DiscourseWorkflows::ExecutionStat.create!(
+ workflow_id: workflow.id,
+ date: 10.days.ago.to_date,
+ total_runs: 2,
+ )
+ DiscourseWorkflows::ExecutionStat.create!(
+ workflow_id: workflow.id,
+ date: 45.days.ago.to_date,
+ total_runs: 5,
+ )
expect(described_class.executions).to eq(
last_day: 3,
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb
index bc6535f636e..afae7ff46ec 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb
@@ -1,32 +1,29 @@
# frozen_string_literal: true
RSpec.describe DiscourseWorkflows::WebhookRequestParser do
- def build_request(
- body: "",
- content_type: "application/json",
- content_length: nil,
- env_overrides: {}
- )
- env = {
+ let(:body) { "" }
+ let(:content_type) { "application/json" }
+ let(:content_length) { body.bytesize }
+ let(:request_env) do
+ {
"CONTENT_TYPE" => content_type,
- "CONTENT_LENGTH" => (content_length || body.bytesize).to_s,
+ "CONTENT_LENGTH" => content_length.to_s,
"HTTP_ACCEPT" => "application/json",
"HTTP_X_CUSTOM" => "custom-value",
"HTTP_AUTHORIZATION" => "Bearer secret",
"HTTP_COOKIE" => "session=abc",
"SERVER_NAME" => "localhost",
- }.merge(env_overrides)
-
- req = instance_double(ActionDispatch::Request)
- allow(req).to receive(:content_type).and_return(content_type)
- allow(req).to receive(:content_length).and_return(content_length || body.bytesize)
- allow(req).to receive(:raw_post).and_return(body)
-
- headers = instance_double(ActionDispatch::Http::Headers)
- allow(headers).to receive(:env).and_return(env)
- allow(req).to receive(:headers).and_return(headers)
-
- req
+ }
+ end
+ let(:headers) { instance_double(ActionDispatch::Http::Headers, env: request_env) }
+ let(:request) do
+ instance_double(
+ ActionDispatch::Request,
+ content_type: content_type,
+ content_length: content_length,
+ raw_post: body,
+ headers: headers,
+ )
end
let(:params) do
@@ -39,59 +36,72 @@ RSpec.describe DiscourseWorkflows::WebhookRequestParser do
data: "test",
)
end
+ let(:parser) { described_class.new(request, params) }
describe "#parse_body" do
- it "parses a valid JSON body" do
- request = build_request(body: '{"foo": "bar"}')
- parser = described_class.new(request, params)
- expect(parser.parse_body).to eq("foo" => "bar")
+ context "with a valid JSON body" do
+ let(:body) { '{"foo": "bar"}' }
+
+ it "parses the body" do
+ expect(parser.parse_body).to eq("foo" => "bar")
+ end
end
- it "returns empty hash for empty JSON body" do
- request = build_request(body: "{}")
- parser = described_class.new(request, params)
- expect(parser.parse_body).to eq({})
+ context "with an empty JSON object" do
+ let(:body) { "{}" }
+
+ it "returns an empty hash" do
+ expect(parser.parse_body).to eq({})
+ end
end
- it "raises on invalid JSON" do
- request = build_request(body: "not json{")
- parser = described_class.new(request, params)
- expect { parser.parse_body }.to raise_error(Discourse::InvalidParameters, /Invalid JSON/)
+ context "with invalid JSON" do
+ let(:body) { "not json{" }
+
+ it "raises an invalid parameters error" do
+ expect { parser.parse_body }.to raise_error(Discourse::InvalidParameters, /Invalid JSON/)
+ end
end
- it "falls back to params for non-JSON content type" do
- request = build_request(body: "data=test", content_type: "application/x-www-form-urlencoded")
- parser = described_class.new(request, params)
- result = parser.parse_body
- expect(result).to eq("data" => "test")
- expect(result).not_to have_key("path")
- expect(result).not_to have_key("listener_id")
+ context "with a non-JSON content type" do
+ let(:body) { "data=test" }
+ let(:content_type) { "application/x-www-form-urlencoded" }
+
+ it "falls back to filtered params" do
+ result = parser.parse_body
+ expect(result).to eq("data" => "test")
+ expect(result).not_to have_key("path")
+ expect(result).not_to have_key("listener_id")
+ end
end
- it "raises when content_length exceeds max" do
- request = build_request(body: "x", content_length: 2.megabytes)
- parser = described_class.new(request, params)
- expect { parser.parse_body }.to raise_error(
- Discourse::InvalidParameters,
- /Request body too large/,
- )
+ context "when content length exceeds the maximum" do
+ let(:body) { "x" }
+ let(:content_length) { 2.megabytes }
+
+ it "raises an invalid parameters error" do
+ expect { parser.parse_body }.to raise_error(
+ Discourse::InvalidParameters,
+ /Request body too large/,
+ )
+ end
end
- it "raises when raw_post exceeds max" do
- large_body = "x" * (1.megabyte + 1)
- request = build_request(body: large_body, content_length: 100)
- parser = described_class.new(request, params)
- expect { parser.parse_body }.to raise_error(
- Discourse::InvalidParameters,
- /Request body too large/,
- )
+ context "when the raw body exceeds the maximum" do
+ let(:body) { "x" * (1.megabyte + 1) }
+ let(:content_length) { 100 }
+
+ it "raises an invalid parameters error" do
+ expect { parser.parse_body }.to raise_error(
+ Discourse::InvalidParameters,
+ /Request body too large/,
+ )
+ end
end
end
describe "#extract_headers" do
it "extracts HTTP_ prefixed headers as lowercase dashed names" do
- request = build_request
- parser = described_class.new(request, params)
headers = parser.extract_headers
expect(headers["accept"]).to eq("application/json")
@@ -99,16 +109,12 @@ RSpec.describe DiscourseWorkflows::WebhookRequestParser do
end
it "includes unprefixed content-type and content-length" do
- request = build_request
- parser = described_class.new(request, params)
headers = parser.extract_headers
expect(headers["content-type"]).to eq("application/json")
end
it "filters sensitive headers" do
- request = build_request
- parser = described_class.new(request, params)
headers = parser.extract_headers
expect(headers["authorization"]).to eq("[FILTERED]")
@@ -116,8 +122,6 @@ RSpec.describe DiscourseWorkflows::WebhookRequestParser do
end
it "skips non-HTTP rack variables" do
- request = build_request
- parser = described_class.new(request, params)
headers = parser.extract_headers
expect(headers).not_to have_key("SERVER_NAME")
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
index 7fae67ed05e..07c7ec37085 100644
--- a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
@@ -7,11 +7,6 @@ RSpec.describe DiscourseWorkflows::WorkflowDependency do
before { described_class.clear_cache! }
after { described_class.clear_cache! }
- def index(workflow)
- version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
- DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: version)
- end
-
describe ".active_node_types" do
it "returns the node types referenced by the active version of a published workflow" do
graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:topic_closed" }
@@ -44,7 +39,8 @@ RSpec.describe DiscourseWorkflows::WorkflowDependency do
g.chain "t1", "m1"
end
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
- index(workflow)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version:)
expect(described_class.cached_user_modals?).to eq(true)
end
@@ -57,7 +53,8 @@ RSpec.describe DiscourseWorkflows::WorkflowDependency do
g.chain "t1", "a1"
end
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
- index(workflow)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version:)
expect(described_class.cached_user_modals?).to eq(false)
end
diff --git a/plugins/discourse-workflows/spec/plugin_helper.rb b/plugins/discourse-workflows/spec/plugin_helper.rb
index f270130b524..d9efb2c6f79 100644
--- a/plugins/discourse-workflows/spec/plugin_helper.rb
+++ b/plugins/discourse-workflows/spec/plugin_helper.rb
@@ -1,7 +1,5 @@
# frozen_string_literal: true
-Dir[File.join(__dir__, "support", "**", "*.rb")].each { |f| require f }
-
module DiscourseWorkflowsSpecHelper
extend ActiveSupport::Concern
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
index 7cf747766eb..14dd006a982 100644
--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
@@ -161,7 +161,7 @@ RSpec.describe DiscourseWorkflows::ExecutionsController do
describe "GET /admin/plugins/discourse-workflows/executions/:id" do
fab!(:execution) { Fabricate(:discourse_workflows_completed_execution, workflow: workflow) }
- before { Fabricate(:discourse_workflows_execution_data_with_steps, execution: execution) }
+ let!(:execution_data) { Fabricate(:discourse_workflows_execution_data_with_steps, execution:) }
it "returns the execution with steps" do
get "/admin/plugins/discourse-workflows/executions/#{execution.id}.json"
diff --git a/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb b/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
index 39374396718..064e9d66cb1 100644
--- a/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
+++ b/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
@@ -4,44 +4,41 @@ RSpec.describe CurrentUserSerializer do
fab!(:admin)
fab!(:user)
- before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
-
- def serialized(target)
- JSON.parse(described_class.new(target, scope: Guardian.new(target), root: false).to_json)
+ subject(:serialized_user) do
+ JSON.parse(described_class.new(user, scope: user.guardian, root: false).to_json)
end
- def index_modal_workflow
- graph =
- build_workflow_graph do |g|
- g.node "t1", "trigger:manual"
- g.node "m1",
- "action:modal",
- configuration: {
- "title" => "Approve?",
- "buttons" => {
- "values" => [{ "label" => "Approve", "value" => "approve" }],
- },
- }
- g.chain "t1", "m1"
- end
- workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
- version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
- DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: version)
- end
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
describe "discourse_workflows_user_modal_last_id" do
it "is omitted when no workflow uses a modal node" do
- expect(serialized(user)).not_to have_key("discourse_workflows_user_modal_last_id")
+ expect(serialized_user).not_to have_key("discourse_workflows_user_modal_last_id")
end
it "is the channel's last id when a workflow uses a modal node" do
- index_modal_workflow
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:manual"
+ g.node "m1",
+ "action:modal",
+ configuration: {
+ "title" => "Approve?",
+ "buttons" => {
+ "values" => [{ "label" => "Approve", "value" => "approve" }],
+ },
+ }
+ g.chain "t1", "m1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version:)
+
channel = DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)
MessageBus.publish(channel, { type: "show_modal" }, user_ids: [user.id])
- payload = serialized(user)
-
- expect(payload["discourse_workflows_user_modal_last_id"]).to eq(MessageBus.last_id(channel))
+ expect(serialized_user["discourse_workflows_user_modal_last_id"]).to eq(
+ MessageBus.last_id(channel),
+ )
end
end
end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
index fb7137ab69d..f916175bc7b 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
@@ -6,7 +6,10 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
fab!(:user)
- def create_waiting_execution(timeout_minutes: nil, timeout_action: nil, limit_wait_time: true)
+ let(:timeout_minutes) { nil }
+ let(:timeout_action) { nil }
+ let(:limit_wait_time) { true }
+ let(:waiting_execution) do
configuration = { "resume" => "webhook", "limit_wait_time" => limit_wait_time }
if limit_wait_time
configuration["timeout_amount"] = timeout_minutes
@@ -23,7 +26,7 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
- execution.update!(timeout_action: timeout_action) if timeout_action
+ execution.update!(timeout_action:) if timeout_action
execution
end
@@ -38,18 +41,20 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
end
context "when timeout_action is fail" do
+ let(:timeout_minutes) { 30 }
+ let(:timeout_action) { "fail" }
+
it "fails the expired execution" do
freeze_time
- execution = create_waiting_execution(timeout_minutes: 30, timeout_action: "fail")
- expect(execution.status).to eq("waiting")
+ expect(waiting_execution.status).to eq("waiting")
freeze_time(31.minutes.from_now)
result
- execution.reload
- expect(execution.status).to eq("error")
- expect(execution.error).to eq("Approval timed out")
+ waiting_execution.reload
+ expect(waiting_execution.status).to eq("error")
+ expect(waiting_execution.error).to eq("Approval timed out")
end
end
@@ -74,25 +79,28 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
end
context "when execution has not timed out" do
+ let(:timeout_minutes) { 60 }
+ let(:timeout_action) { "fail" }
+
it "does not expire the execution" do
freeze_time
- execution = create_waiting_execution(timeout_minutes: 60, timeout_action: "fail")
+ waiting_execution
freeze_time(30.minutes.from_now)
result
- expect(execution.reload.status).to eq("waiting")
+ expect(waiting_execution.reload.status).to eq("waiting")
end
end
context "when execution uses the default wait ceiling" do
+ let(:limit_wait_time) { false }
+
it "expires after the executor timeout" do
freeze_time
- execution = create_waiting_execution(limit_wait_time: false)
-
- expect(execution.waiting_until).to eq_time(
+ expect(waiting_execution.waiting_until).to eq_time(
DiscourseWorkflows::Executor::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
)
@@ -101,7 +109,7 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
)
result
- expect(execution.reload.status).to eq("success")
+ expect(waiting_execution.reload.status).to eq("success")
end
end
end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
index 8b8033b3564..9ad13f76d3c 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
@@ -11,7 +11,17 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
fab!(:user)
let(:dependencies) { { guardian: user.guardian } }
- let(:params) { { action_id: action_id("approve") } }
+ let(:action) { "approve" }
+ let(:target_user_id) { user.id }
+ let(:action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ action:,
+ target_user_id:,
+ )
+ end
+ let(:params) { { action_id: } }
fab!(:workflow) do
graph =
@@ -47,15 +57,6 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
).run
end
- def action_id(action, target_user_id: user.id)
- DiscourseWorkflows::InteractiveResume.action_id(
- execution_id: execution.id,
- resume_token: execution.resume_token,
- action: action,
- target_user_id: target_user_id,
- )
- end
-
it "pauses at the modal node before being resumed" do
expect(execution.status).to eq("waiting")
end
@@ -85,7 +86,7 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
end
context "when the action is not one of the configured buttons" do
- let(:params) { { action_id: action_id("delete") } }
+ let(:action) { "delete" }
it { is_expected.to fail_to_find_a_model(:resume_request) }
end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb
index 7c2e0e60af7..4969c8a9a09 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb
@@ -89,7 +89,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Action::BuildExpressionPreviewConte
context "with a successful trigger run" do
let(:items) { [{ "json" => { "title" => "From past run" } }] }
- before do
+ let!(:execution_data) do
Fabricate(
:discourse_workflows_execution_data,
execution: execution,
@@ -296,7 +296,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Action::BuildExpressionPreviewConte
Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
end
- before do
+ let!(:execution_data) do
Fabricate(
:discourse_workflows_execution_data,
execution:
@@ -365,7 +365,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Action::BuildExpressionPreviewConte
end
context "with a successful non-trigger run" do
- before do
+ let!(:execution_data) do
Fabricate(
:discourse_workflows_execution_data,
execution: execution,
@@ -397,7 +397,7 @@ RSpec.describe DiscourseWorkflows::Workflow::Action::BuildExpressionPreviewConte
end
context "with no successful run" do
- before do
+ let!(:execution_data) do
Fabricate(
:discourse_workflows_execution_data,
execution: execution,
diff --git a/plugins/poll/spec/jobs/scheduled/clean_up_inactive_users_spec.rb b/plugins/poll/spec/jobs/scheduled/clean_up_inactive_users_spec.rb
index 053379780a2..ce76ba1e11d 100644
--- a/plugins/poll/spec/jobs/scheduled/clean_up_inactive_users_spec.rb
+++ b/plugins/poll/spec/jobs/scheduled/clean_up_inactive_users_spec.rb
@@ -3,7 +3,7 @@
describe Jobs::CleanUpInactiveUsers do
before { SiteSetting.clean_up_inactive_users_after_days = 4 }
- def inactive_user
+ let(:inactive_user) do
Fabricate(
:user,
created_at: 5.days.ago,
@@ -13,19 +13,18 @@ describe Jobs::CleanUpInactiveUsers do
end
it "does not delete users who have cast poll votes" do
- user = inactive_user
poll = Fabricate(:poll)
option = Fabricate(:poll_option, poll: poll)
- Fabricate(:poll_vote, poll: poll, poll_option: option, user: user)
+ Fabricate(:poll_vote, poll: poll, poll_option: option, user: inactive_user)
expect { described_class.new.execute({}) }.not_to change { User.count }
- expect(User.exists?(user.id)).to eq(true)
+ expect(User.exists?(inactive_user.id)).to eq(true)
end
it "deletes inactive users who have never voted in a poll" do
- user = inactive_user
+ inactive_user
expect { described_class.new.execute({}) }.to change { User.count }.by(-1)
- expect(User.exists?(user.id)).to eq(false)
+ expect(User.exists?(inactive_user.id)).to eq(false)
end
end
diff --git a/plugins/poll/spec/lib/polls_updater_spec.rb b/plugins/poll/spec/lib/polls_updater_spec.rb
index c5f0bd01d6f..933840e6de3 100644
--- a/plugins/poll/spec/lib/polls_updater_spec.rb
+++ b/plugins/poll/spec/lib/polls_updater_spec.rb
@@ -1,10 +1,6 @@
# frozen_string_literal: true
RSpec.describe DiscoursePoll::PollsUpdater do
- def update(post, polls)
- DiscoursePoll::PollsUpdater.update(post, polls)
- end
-
let(:user) { Fabricate(:user) }
let(:post) { Fabricate(:post, raw: <<~RAW) }
@@ -42,7 +38,10 @@ RSpec.describe DiscoursePoll::PollsUpdater do
describe "update" do
it "does nothing when there are no changes" do
- message = MessageBus.track_publish("/polls/#{post.topic_id}") { update(post, polls) }.first
+ message =
+ MessageBus
+ .track_publish("/polls/#{post.topic_id}") { described_class.update(post, polls) }
+ .first
expect(message).to be(nil)
end
@@ -65,7 +64,7 @@ RSpec.describe DiscoursePoll::PollsUpdater do
DiscoursePoll::Poll.toggle_status(post.user, post.id, "poll", "closed")
freeze_time (SiteSetting.poll_edit_window_mins + 1).minutes.from_now
- update(post, DiscoursePoll::PollsValidator.new(post).validate_polls)
+ described_class.update(post, DiscoursePoll::PollsValidator.new(post).validate_polls)
expect(post.errors[:base].size).to equal(0)
end
@@ -73,7 +72,7 @@ RSpec.describe DiscoursePoll::PollsUpdater do
describe "deletes polls" do
it "that were removed" do
- update(post, {})
+ described_class.update(post, {})
post.reload
@@ -88,7 +87,10 @@ RSpec.describe DiscoursePoll::PollsUpdater do
expect(Poll.find_by(post: post)).to_not be
- message = MessageBus.track_publish("/polls/#{post.topic_id}") { update(post, polls) }.first
+ message =
+ MessageBus
+ .track_publish("/polls/#{post.topic_id}") { described_class.update(post, polls) }
+ .first
poll = Poll.find_by(post: post)
@@ -147,7 +149,9 @@ RSpec.describe DiscoursePoll::PollsUpdater do
message =
MessageBus
- .track_publish("/polls/#{post.topic_id}") { update(post, polls_with_some_attributes) }
+ .track_publish("/polls/#{post.topic_id}") do
+ described_class.update(post, polls_with_some_attributes)
+ end
.first
poll = Poll.find_by(post: post)
@@ -177,7 +181,7 @@ RSpec.describe DiscoursePoll::PollsUpdater do
message =
MessageBus
.track_publish("/polls/#{post.topic_id}") do
- update(post, polls_with_some_attributes)
+ described_class.update(post, polls_with_some_attributes)
end
.first
@@ -202,7 +206,7 @@ RSpec.describe DiscoursePoll::PollsUpdater do
freeze_time (edit_window + 1).minutes.from_now
- update(post, polls_with_some_attributes)
+ described_class.update(post, polls_with_some_attributes)
poll = Poll.find_by(post: post)
diff --git a/plugins/poll/spec/lib/pretty_text_spec.rb b/plugins/poll/spec/lib/pretty_text_spec.rb
index 6fa28c08feb..f3c0e0b894a 100644
--- a/plugins/poll/spec/lib/pretty_text_spec.rb
+++ b/plugins/poll/spec/lib/pretty_text_spec.rb
@@ -1,10 +1,6 @@
# frozen_string_literal: true
RSpec.describe PrettyText do
- def n(html)
- html.strip
- end
-
it "supports multi choice polls" do
cooked = PrettyText.cook <<~MD
[poll type=multiple min=1 max=3 public=true]
@@ -112,7 +108,7 @@ RSpec.describe PrettyText do
HTML
# note, hashes should remain stable even if emoji changes cause text content is hashed
- expect(n cooked).to eq(n expected)
+ expect(cooked.strip).to eq(expected.strip)
end
it "can onebox posts" do
diff --git a/plugins/poll/spec/serializers/poll_option_serializer_spec.rb b/plugins/poll/spec/serializers/poll_option_serializer_spec.rb
index a6eff33c33b..34210a90def 100644
--- a/plugins/poll/spec/serializers/poll_option_serializer_spec.rb
+++ b/plugins/poll/spec/serializers/poll_option_serializer_spec.rb
@@ -1,16 +1,16 @@
# frozen_string_literal: true
-def serialize_option(option, user)
- PollOptionSerializer.new(
- option,
- root: false,
- scope: {
- can_see_results: poll.can_see_results?(user),
- },
- )
-end
-
RSpec.describe PollOptionSerializer do
+ subject(:serializer) do
+ described_class.new(
+ poll.poll_options.first,
+ root: false,
+ scope: {
+ can_see_results: poll.can_see_results?(viewer),
+ },
+ )
+ end
+
let(:voter) { Fabricate(:user) }
let(:poll) { post.polls.first }
@@ -20,11 +20,9 @@ RSpec.describe PollOptionSerializer do
let(:post) { Fabricate(:post, raw: "[poll]\n- A\n- B\n[/poll]") }
context "when user is not staff" do
- let(:user) { Fabricate(:user) }
+ let(:viewer) { Fabricate(:user) }
it "include votes" do
- serializer = serialize_option(poll.poll_options.first, user)
-
expect(serializer.include_votes?).to eq(true)
end
end
@@ -34,21 +32,17 @@ RSpec.describe PollOptionSerializer do
let(:post) { Fabricate(:post, raw: "[poll results=staff_only]\n- A\n- B\n[/poll]") }
context "when user is not staff" do
- let(:user) { Fabricate(:user) }
+ let(:viewer) { Fabricate(:user) }
it "doesn’t include votes" do
- serializer = serialize_option(poll.poll_options.first, user)
-
expect(serializer.include_votes?).to eq(false)
end
end
context "when user is staff" do
- let(:admin) { Fabricate(:admin) }
+ let(:viewer) { Fabricate(:admin) }
it "includes votes" do
- serializer = serialize_option(poll.poll_options.first, admin)
-
expect(serializer.include_votes?).to eq(true)
end
end
diff --git a/plugins/poll/spec/system/dynamic_polls_spec.rb b/plugins/poll/spec/system/dynamic_polls_spec.rb
index 56e4b6785e3..c56738d9646 100644
--- a/plugins/poll/spec/system/dynamic_polls_spec.rb
+++ b/plugins/poll/spec/system/dynamic_polls_spec.rb
@@ -12,12 +12,8 @@ describe "Dynamic polls" do
SiteSetting.poll_create_allowed_groups = Group::AUTO_GROUPS[:admins].to_s
end
- def cook_poll(raw)
- PostCreator.create!(admin, topic_id: topic.id, raw: raw)
- end
-
it "allows editing poll options after window while preserving votes on existing options" do
- post = cook_poll(<<~MD)
+ post = PostCreator.create!(admin, topic_id: topic.id, raw: <<~MD)
[poll dynamic=true]
* A
* B
diff --git a/plugins/spoiler-alert/spec/pretty_text_spec.rb b/plugins/spoiler-alert/spec/pretty_text_spec.rb
index 494c43f46c3..abeeb8a7894 100644
--- a/plugins/spoiler-alert/spec/pretty_text_spec.rb
+++ b/plugins/spoiler-alert/spec/pretty_text_spec.rb
@@ -3,10 +3,6 @@
describe PrettyText do
let(:post) { Fabricate(:post) }
- def n(html)
- html.strip
- end
-
it "can spoil blocks" do
md = PrettyText.cook("[spoiler]\nmy tests fail\n[/spoiler]")
html = "<div class=\"spoiler\">\n<p>my tests fail</p>\n</div>"
diff --git a/spec/jobs/clean_up_uploads_spec.rb b/spec/jobs/clean_up_uploads_spec.rb
index 834964265c1..6a81baa9243 100644
--- a/spec/jobs/clean_up_uploads_spec.rb
+++ b/spec/jobs/clean_up_uploads_spec.rb
@@ -1,12 +1,8 @@
# frozen_string_literal: true
RSpec.describe Jobs::CleanUpUploads do
- def fabricate_upload(attributes = {})
- Fabricate(:upload, { created_at: 2.hours.ago }.merge(attributes))
- end
-
fab! :expired_upload do
- fabricate_upload
+ Fabricate(:upload, created_at: 2.hours.ago)
end
before do
@@ -22,12 +18,12 @@ RSpec.describe Jobs::CleanUpUploads do
it "only runs upload cleanup every grace period / 2 time" do
SiteSetting.clean_orphan_uploads_grace_period_hours = 48
- expired = fabricate_upload(created_at: 49.hours.ago)
+ expired = Fabricate(:upload, created_at: 49.hours.ago)
Jobs::CleanUpUploads.new.execute(nil)
expect(Upload.exists?(id: expired.id)).to eq(false)
- upload = fabricate_upload(created_at: 72.hours.ago)
+ upload = Fabricate(:upload, created_at: 72.hours.ago)
Jobs::CleanUpUploads.new.execute(nil)
expect(Upload.exists?(id: upload.id)).to eq(true)
@@ -56,8 +52,8 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "deletes other uploads not skipped by an unused callback" do
- expired_upload2 = fabricate_upload
- upload = fabricate_upload
+ expired_upload2 = Fabricate(:upload, created_at: 2.hours.ago)
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
UploadReference.create(target: Fabricate(:post), upload: upload)
expect do Jobs::CleanUpUploads.new.execute(nil) end.to change { Upload.count }.by(-1)
@@ -80,8 +76,8 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "deletes other uploads that are not in use by callback" do
- expired_upload2 = fabricate_upload
- upload = fabricate_upload
+ expired_upload2 = Fabricate(:upload, created_at: 2.hours.ago)
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
UploadReference.create(target: Fabricate(:post), upload: upload)
expect do Jobs::CleanUpUploads.new.execute(nil) end.to change { Upload.count }.by(-1)
@@ -96,7 +92,7 @@ RSpec.describe Jobs::CleanUpUploads do
before { SiteSetting.clean_up_uploads = false }
it "should still delete invalid upload records" do
- upload2 = fabricate_upload(url: "", retain_hours: nil)
+ upload2 = Fabricate(:upload, created_at: 2.hours.ago, url: "", retain_hours: nil)
expect do Jobs::CleanUpUploads.new.execute(nil) end.to change { Upload.count }.by(-1)
@@ -110,16 +106,16 @@ RSpec.describe Jobs::CleanUpUploads do
SiteSetting.provider = SiteSettings::DbProvider.new(SiteSetting)
SiteSetting.clean_orphan_uploads_grace_period_hours = 1
- system_upload = fabricate_upload(id: -999)
- logo_upload = fabricate_upload
- logo_small_upload = fabricate_upload
- digest_logo_upload = fabricate_upload
- mobile_logo_upload = fabricate_upload
- large_icon_upload = fabricate_upload
- opengraph_image_upload = fabricate_upload
- x_summary_large_image_upload = fabricate_upload
- favicon_upload = fabricate_upload
- apple_touch_icon_upload = fabricate_upload
+ system_upload = Fabricate(:upload, created_at: 2.hours.ago, id: -999)
+ logo_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ logo_small_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ digest_logo_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ mobile_logo_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ large_icon_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ opengraph_image_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ x_summary_large_image_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ favicon_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ apple_touch_icon_upload = Fabricate(:upload, created_at: 2.hours.ago)
SiteSetting.logo = logo_upload
SiteSetting.logo_small = logo_small_upload
@@ -148,7 +144,7 @@ RSpec.describe Jobs::CleanUpUploads do
system_upload,
].each { |record| expect(Upload.exists?(id: record.id)).to eq(true) }
- fabricate_upload
+ Fabricate(:upload, created_at: 2.hours.ago)
SiteSetting.opengraph_image = ""
Jobs::CleanUpUploads.new.execute(nil)
@@ -162,8 +158,8 @@ RSpec.describe Jobs::CleanUpUploads do
SiteSetting.provider = SiteSettings::DbProvider.new(SiteSetting)
SiteSetting.clean_orphan_uploads_grace_period_hours = 1
- avatar1_upload = fabricate_upload
- avatar2_upload = fabricate_upload
+ avatar1_upload = Fabricate(:upload, created_at: 2.hours.ago)
+ avatar2_upload = Fabricate(:upload, created_at: 2.hours.ago)
SiteSetting.selectable_avatars = [avatar1_upload, avatar2_upload]
@@ -178,7 +174,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete profile background uploads" do
- profile_background_upload = fabricate_upload
+ profile_background_upload = Fabricate(:upload, created_at: 2.hours.ago)
UserProfile.last.upload_profile_background(profile_background_upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -188,7 +184,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete card background uploads" do
- card_background_upload = fabricate_upload
+ card_background_upload = Fabricate(:upload, created_at: 2.hours.ago)
UserProfile.last.upload_card_background(card_background_upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -198,7 +194,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete category logo uploads" do
- category_logo_upload = fabricate_upload
+ category_logo_upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:category, uploaded_logo: category_logo_upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -208,7 +204,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete category dark logo uploads" do
- category_logo_dark_upload = fabricate_upload
+ category_logo_dark_upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:category, uploaded_logo_dark: category_logo_dark_upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -218,7 +214,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete category background uploads" do
- category_background_upload = fabricate_upload
+ category_background_upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:category, uploaded_background: category_background_upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -228,7 +224,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete category dark background uploads" do
- category_background_dark_upload = fabricate_upload
+ category_background_dark_upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:category, uploaded_background_dark: category_background_dark_upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -238,7 +234,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete post uploads" do
- upload = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:post, uploads: [upload])
Jobs::CleanUpUploads.new.execute(nil)
@@ -248,7 +244,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete user uploaded avatar" do
- upload = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:user, uploaded_avatar: upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -258,7 +254,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete user gravatar" do
- upload = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:user, user_avatar: Fabricate(:user_avatar, gravatar_upload: upload))
Jobs::CleanUpUploads.new.execute(nil)
@@ -268,7 +264,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete user custom upload" do
- upload = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(:user, user_avatar: Fabricate(:user_avatar, custom_upload: upload))
Jobs::CleanUpUploads.new.execute(nil)
@@ -278,9 +274,9 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete uploads in a queued post" do
- upload = fabricate_upload
- upload2 = fabricate_upload
- upload3 = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
+ upload2 = Fabricate(:upload, created_at: 2.hours.ago)
+ upload3 = Fabricate(:upload, created_at: 2.hours.ago)
Fabricate(
:reviewable_queued_post_topic,
@@ -307,8 +303,8 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete uploads in a draft" do
- upload = fabricate_upload
- upload2 = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
+ upload2 = Fabricate(:upload, created_at: 2.hours.ago)
Draft.set(Fabricate(:user), "test", 0, "upload://#{upload.sha1}\n#{upload2.short_url}")
@@ -320,7 +316,13 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete uploads with an access control post ID that are marked secure" do
- secure_upload = fabricate_upload(access_control_post_id: Fabricate(:post).id, secure: true)
+ secure_upload =
+ Fabricate(
+ :upload,
+ created_at: 2.hours.ago,
+ access_control_post_id: Fabricate(:post).id,
+ secure: true,
+ )
Jobs::CleanUpUploads.new.execute(nil)
@@ -329,7 +331,13 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does delete uploads with an access control post ID that are not marked secure" do
- secure_upload = fabricate_upload(access_control_post_id: Fabricate(:post).id, secure: false)
+ secure_upload =
+ Fabricate(
+ :upload,
+ created_at: 2.hours.ago,
+ access_control_post_id: Fabricate(:post).id,
+ secure: false,
+ )
Jobs::CleanUpUploads.new.execute(nil)
@@ -338,7 +346,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete custom emojis" do
- upload = fabricate_upload
+ upload = Fabricate(:upload, created_at: 2.hours.ago)
CustomEmoji.create!(name: "test", upload: upload)
Jobs::CleanUpUploads.new.execute(nil)
@@ -348,7 +356,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete user exported csv uploads" do
- csv_file = fabricate_upload
+ csv_file = Fabricate(:upload, created_at: 2.hours.ago)
UserExport.create(file_name: "export.csv", user_id: Fabricate(:user).id, upload_id: csv_file.id)
Jobs::CleanUpUploads.new.execute(nil)
@@ -359,7 +367,7 @@ RSpec.describe Jobs::CleanUpUploads do
it "does not delete theme setting uploads" do
theme = Fabricate(:theme)
- theme_upload = fabricate_upload
+ theme_upload = Fabricate(:upload, created_at: 2.hours.ago)
ThemeSetting.create!(
theme: theme,
data_type: ThemeSetting.types[:upload],
@@ -374,7 +382,7 @@ RSpec.describe Jobs::CleanUpUploads do
end
it "does not delete badges uploads" do
- badge_image = fabricate_upload
+ badge_image = Fabricate(:upload, created_at: 2.hours.ago)
badge = Fabricate(:badge, image_upload_id: badge_image.id)
Jobs::CleanUpUploads.new.execute(nil)
diff --git a/spec/jobs/deliver_push_notification_spec.rb b/spec/jobs/deliver_push_notification_spec.rb
index 963879f5a58..73804a69911 100644
--- a/spec/jobs/deliver_push_notification_spec.rb
+++ b/spec/jobs/deliver_push_notification_spec.rb
@@ -18,7 +18,7 @@ RSpec.describe Jobs::DeliverPushNotification do
end
describe "time window gate" do
- before { Fabricate(:push_subscription, user: user) }
+ fab!(:time_window_push_subscription) { Fabricate(:push_subscription, user: user) }
it "does not deliver when user is missing" do
PushNotificationPusher.expects(:push).never
diff --git a/spec/jobs/export_user_archive_spec.rb b/spec/jobs/export_user_archive_spec.rb
index 455a7889255..9ef3c0300eb 100644
--- a/spec/jobs/export_user_archive_spec.rb
+++ b/spec/jobs/export_user_archive_spec.rb
@@ -36,10 +36,6 @@ RSpec.describe Jobs::ExportUserArchive do
[data_rows, csv_out]
end
- def make_component_json
- JSON.parse(MultiJson.dump(job.public_send(:"#{component}_export")))
- end
-
describe "#execute" do
before do
_ = post
@@ -257,7 +253,7 @@ RSpec.describe Jobs::ExportUserArchive do
it "properly includes the profile fields" do
_serializer = job.preferences_export
# puts MultiJson.dump(serializer, indent: 4)
- output = make_component_json
+ output = JSON.parse(MultiJson.dump(job.public_send(:"#{component}_export")))
payload = output["user"]
expect(payload["website"]).to match("doe.example.com")
diff --git a/spec/jobs/sync_access_control_for_uploads_spec.rb b/spec/jobs/sync_access_control_for_uploads_spec.rb
index 953e601ef1f..7f98a304bc1 100644
--- a/spec/jobs/sync_access_control_for_uploads_spec.rb
+++ b/spec/jobs/sync_access_control_for_uploads_spec.rb
@@ -1,15 +1,13 @@
# frozen_string_literal: true
RSpec.describe Jobs::SyncAccessControlForUploads do
+ subject(:run_job) { described_class.new.execute(upload_ids: upload_ids) }
+
let(:upload1) { Fabricate(:upload) }
let(:upload2) { Fabricate(:upload) }
let(:upload3) { Fabricate(:secure_upload) }
let(:upload_ids) { [upload1.id, upload2.id, upload3.id] }
- def run_job
- described_class.new.execute(upload_ids: upload_ids)
- end
-
it "does nothing if not using external storage" do
Upload.expects(:where).never
run_job
diff --git a/spec/lib/email/receiver_spec.rb b/spec/lib/email/receiver_spec.rb
index 80c9662d0d0..e2a447bed74 100644
--- a/spec/lib/email/receiver_spec.rb
+++ b/spec/lib/email/receiver_spec.rb
@@ -1814,12 +1814,13 @@ RSpec.describe Email::Receiver do
SiteSetting.whispers_allowed_groups = "#{Group::AUTO_GROUPS[:staff]}"
end
- def create_post_reply_key(value)
- Fabricate(:post_reply_key, reply_key: value, user: user2, post: post)
- end
-
it "when bounce without verp" do
- create_post_reply_key("4f97315cc828096c9cb34c6f1a0d6fe8")
+ Fabricate(
+ :post_reply_key,
+ reply_key: "4f97315cc828096c9cb34c6f1a0d6fe8",
+ user: user2,
+ post: post,
+ )
expect { process(:bounced_email) }.to raise_error(Email::Receiver::BouncedEmailError)
post = Post.last
@@ -1836,10 +1837,10 @@ RSpec.describe Email::Receiver do
context "when bounce with verp" do
let(:bounce_key) { "14b08c855160d67f2e0c2f8ef36e251e" }
-
- before do
- SiteSetting.reply_by_email_address = "foo+%{reply_key}@discourse.org"
- create_post_reply_key(bounce_key)
+ let!(:bounce_post_reply_key) do
+ Fabricate(:post_reply_key, reply_key: bounce_key, user: user2, post: post)
+ end
+ let!(:bounce_email_log) do
Fabricate(
:email_log,
to_address: email_address,
@@ -1849,6 +1850,8 @@ RSpec.describe Email::Receiver do
)
end
+ before { SiteSetting.reply_by_email_address = "foo+%{reply_key}@discourse.org" }
+
it "creates a post with the bounce error" do
expect { process(:hard_bounce_via_verp) }.to raise_error(
Email::Receiver::BouncedEmailError,
diff --git a/spec/lib/ember_assets_spec.rb b/spec/lib/ember_assets_spec.rb
index 6e065c6640d..64ac714743a 100644
--- a/spec/lib/ember_assets_spec.rb
+++ b/spec/lib/ember_assets_spec.rb
@@ -4,12 +4,6 @@ describe EmberAssets do
describe "cache" do
after { EmberAssets.clear_cache! }
- def simulate_request_cache_clearance
- # this method is defined by ActiveSupport::CurrentAttributes
- # and is called before/after every web request
- EmberAssets.reset
- end
-
context "in development" do
before { Rails.env.stubs(:development?).returns(true) }
@@ -17,7 +11,7 @@ describe EmberAssets do
EmberAssets.cache[:foo] = "bar"
expect(EmberAssets.cache[:foo]).to eq("bar")
- simulate_request_cache_clearance
+ EmberAssets.reset
expect(EmberAssets.cache[:foo]).to eq(nil)
end
@@ -30,7 +24,7 @@ describe EmberAssets do
EmberAssets.cache[:foo] = "bar"
expect(EmberAssets.cache[:foo]).to eq("bar")
- simulate_request_cache_clearance
+ EmberAssets.reset
# In production, persists across requests
expect(EmberAssets.cache[:foo]).to eq("bar")
diff --git a/spec/lib/search_spec.rb b/spec/lib/search_spec.rb
index 06a67819948..bd41835d0b9 100644
--- a/spec/lib/search_spec.rb
+++ b/spec/lib/search_spec.rb
@@ -1806,9 +1806,7 @@ RSpec.describe Search do
end
describe "tags" do
- def search
- Search.execute(tag.name)
- end
+ let(:search) { Search.execute(tag.name) }
let!(:tag) { Fabricate(:tag) }
let!(:uppercase_tag) { Fabricate(:tag, name: "HeLlO") }
diff --git a/spec/lib/seed_data/topics_spec.rb b/spec/lib/seed_data/topics_spec.rb
index 0f426b0c5c6..20ff762fed0 100644
--- a/spec/lib/seed_data/topics_spec.rb
+++ b/spec/lib/seed_data/topics_spec.rb
@@ -5,10 +5,9 @@ require "seed_data/topics"
RSpec.describe SeedData::Topics do
subject(:seeder) { SeedData::Topics.with_default_locale }
- before do
- general_category = Fabricate(:category, name: "General")
- SiteSetting.general_category_id = general_category.id
- end
+ fab!(:general_category) { Fabricate(:category, name: "General") }
+
+ before { SiteSetting.general_category_id = general_category.id }
def create_topic(name = "welcome_topic_id")
seeder.create(site_setting_names: [name])
diff --git a/spec/models/concerns/has_post_upload_references_spec.rb b/spec/models/concerns/has_post_upload_references_spec.rb
index a749c0f48e6..21ff09e1722 100644
--- a/spec/models/concerns/has_post_upload_references_spec.rb
+++ b/spec/models/concerns/has_post_upload_references_spec.rb
@@ -87,7 +87,7 @@ RSpec.describe HasPostUploadReferences do
end
it "sets the access_control_post_id on uploads that don't already have the value set" do
- other_target = create_target_with_different_access_control_id
+ other_target = Fabricate(:post)
upload2.update(access_control_post_id: other_target.id)
FileStore::S3Store.any_instance.stubs(:has_been_uploaded?).returns(true)
@@ -181,10 +181,6 @@ RSpec.describe HasPostUploadReferences do
let(:subject) { post }
let(:expected_access_control_post_id) { post.id }
- def create_target_with_different_access_control_id
- Fabricate(:post)
- end
-
include_examples "has upload references"
context "when handling video thumbnails" do
@@ -237,10 +233,6 @@ RSpec.describe HasPostUploadReferences do
let(:subject) { localization }
let(:expected_access_control_post_id) { post.id }
- def create_target_with_different_access_control_id
- Fabricate(:post)
- end
-
include_examples "has upload references"
it "uses the parent post's ID for access control" do
diff --git a/spec/models/ignored_user_spec.rb b/spec/models/ignored_user_spec.rb
index fb4c22efbe9..7da7f90ecb4 100644
--- a/spec/models/ignored_user_spec.rb
+++ b/spec/models/ignored_user_spec.rb
@@ -5,8 +5,7 @@ RSpec.describe IgnoredUser do
fab!(:user)
fab!(:target, :user)
fab!(:admin) { Fabricate(:user, admin: true) }
-
- before { Fabricate(:ignored_user, user: user, ignored_user: target) }
+ fab!(:ignored_target) { Fabricate(:ignored_user, user: user, ignored_user: target) }
it "returns ids of users ignored by the given user" do
expect(described_class.ignored_ids_for(user)).to contain_exactly(target.id)
diff --git a/spec/models/post_timing_spec.rb b/spec/models/post_timing_spec.rb
index e2203254e48..b056b55f0a3 100644
--- a/spec/models/post_timing_spec.rb
+++ b/spec/models/post_timing_spec.rb
@@ -15,29 +15,17 @@ RSpec.describe PostTiming do
p1.topic_id
end
- def timing(user_id, post_number)
- PostTiming.create!(topic_id: topic_id, user_id: user_id, post_number: post_number, msecs: 0)
- end
-
- def topic_user(user_id, last_read_post_number)
- TopicUser.create!(
- topic_id: topic_id,
- user_id: user_id,
- last_read_post_number: last_read_post_number,
- )
- end
-
it "works correctly" do
- timing(1, 1)
- timing(2, 1)
- timing(2, 2)
- timing(3, 1)
- timing(3, 2)
- timing(3, 3)
-
- _tu_one = topic_user(1, 1)
- _tu_two = topic_user(2, 2)
- _tu_three = topic_user(3, 3)
+ PostTiming.create!(topic_id:, user_id: 1, post_number: 1, msecs: 0)
+ PostTiming.create!(topic_id:, user_id: 2, post_number: 1, msecs: 0)
+ PostTiming.create!(topic_id:, user_id: 2, post_number: 2, msecs: 0)
+ PostTiming.create!(topic_id:, user_id: 3, post_number: 1, msecs: 0)
+ PostTiming.create!(topic_id:, user_id: 3, post_number: 2, msecs: 0)
+ PostTiming.create!(topic_id:, user_id: 3, post_number: 3, msecs: 0)
+
+ TopicUser.create!(topic_id:, user_id: 1, last_read_post_number: 1)
+ TopicUser.create!(topic_id:, user_id: 2, last_read_post_number: 2)
+ TopicUser.create!(topic_id:, user_id: 3, last_read_post_number: 3)
PostTiming.pretend_read(topic_id, 2, 3)
diff --git a/spec/models/problem_check_tracker_spec.rb b/spec/models/problem_check_tracker_spec.rb
index ed5b75721d6..08c531705e9 100644
--- a/spec/models/problem_check_tracker_spec.rb
+++ b/spec/models/problem_check_tracker_spec.rb
@@ -27,7 +27,7 @@ RSpec.describe ProblemCheckTracker do
end
describe ".[]" do
- before { Fabricate(:problem_check_tracker, identifier: "twitter_login") }
+ fab!(:twitter_login_tracker) { Fabricate(:problem_check_tracker, identifier: "twitter_login") }
context "when the problem check tracker already exists" do
it { expect(described_class[:twitter_login]).not_to be_new_record }
@@ -39,10 +39,8 @@ RSpec.describe ProblemCheckTracker do
end
describe "#check" do
- before do
- Fabricate(:problem_check_tracker, identifier: "twitter_login")
- Fabricate(:problem_check_tracker, identifier: "missing_check")
- end
+ fab!(:twitter_login_tracker) { Fabricate(:problem_check_tracker, identifier: "twitter_login") }
+ fab!(:missing_check_tracker) { Fabricate(:problem_check_tracker, identifier: "missing_check") }
context "when the tracker has a corresponding check" do
it { expect(described_class[:twitter_login].check.new).to be_a(ProblemCheck) }
@@ -294,8 +292,7 @@ RSpec.describe ProblemCheckTracker do
context "when there's an alarm sounding for multi-target trackers" do
let(:blips) { 1 }
-
- before do
+ let!(:existing_admin_notice) do
Fabricate(
:admin_notice,
subject: "problem",
diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rb
index 54429878848..cb8c6f89f8b 100644
--- a/spec/models/tag_spec.rb
+++ b/spec/models/tag_spec.rb
@@ -1,14 +1,6 @@
# frozen_string_literal: true
RSpec.describe Tag do
- def make_some_tags(count: 3, tag_a_topic: false)
- if tag_a_topic
- Fabricate.times(count, :tag, topics: [Fabricate(:topic)])
- else
- Fabricate.times(count, :tag)
- end
- end
-
let(:tag) { Fabricate(:tag) }
let(:tag2) { Fabricate(:tag) }
let(:topic) { Fabricate(:topic, tags: [tag]) }
@@ -84,7 +76,7 @@ RSpec.describe Tag do
describe "#top_tags" do
context "when nothing has been tagged" do
- let!(:tags) { make_some_tags(tag_a_topic: false) }
+ let!(:tags) { Fabricate.times(3, :tag) }
it "returns nothing" do
expect(Tag.top_tags.sort).to be_empty
@@ -92,7 +84,8 @@ RSpec.describe Tag do
end
context "when something has been tagged" do
- let!(:tags) { make_some_tags(tag_a_topic: true) }
+ let!(:tagged_topic) { Fabricate(:topic) }
+ let!(:tags) { Fabricate.times(3, :tag, topics: [tagged_topic]) }
it "returns all tags" do
expect(Tag.top_tags).to contain_exactly(
@@ -102,7 +95,7 @@ RSpec.describe Tag do
end
context "with categories" do
- let(:tags) { make_some_tags(count: 4) }
+ let(:tags) { Fabricate.times(4, :tag) }
let(:category1) { Fabricate(:category) }
let(:private_category) { Fabricate(:category) }
let!(:topics) do
@@ -147,7 +140,7 @@ RSpec.describe Tag do
end
context "with category-specific tags" do
- let(:tags) { make_some_tags(count: 3) }
+ let(:tags) { Fabricate.times(3, :tag) }
let(:category1) { Fabricate(:category, tags: [tags[0]]) } # only one tag allowed in this category
let(:category2) { Fabricate(:category) }
let!(:topics) do
@@ -277,7 +270,9 @@ RSpec.describe Tag do
)
end
- before { 2.times { |i| Fabricate(:tag, topics: [personal_message], name: "tag-#{i}") } }
+ let!(:personal_message_tags) do
+ 2.times { |i| Fabricate(:tag, topics: [personal_message], name: "tag-#{i}") }
+ end
it "returns nothing if user is not a staff" do
expect(Tag.pm_tags(guardian: Guardian.new(regular_user))).to be_empty
diff --git a/spec/models/topic_link_click_spec.rb b/spec/models/topic_link_click_spec.rb
index 7f26f0dc8e6..c6a38eb91ee 100644
--- a/spec/models/topic_link_click_spec.rb
+++ b/spec/models/topic_link_click_spec.rb
@@ -5,10 +5,6 @@ RSpec.describe TopicLinkClick do
it { is_expected.to belong_to :user }
it { is_expected.to validate_presence_of :topic_link_id }
- def test_uri
- URI.parse("http://test.host")
- end
-
describe "topic_links" do
fab!(:topic) { Fabricate(:topic, user: Fabricate(:user, refresh_auto_groups: true)) }
fab!(:post) { Fabricate(:post_with_external_links, user: topic.user, topic:) }
diff --git a/spec/models/topic_tracking_state_spec.rb b/spec/models/topic_tracking_state_spec.rb
index 48fc9bff570..a865871dd5b 100644
--- a/spec/models/topic_tracking_state_spec.rb
+++ b/spec/models/topic_tracking_state_spec.rb
@@ -199,8 +199,9 @@ RSpec.describe TopicTrackingState do
describe "#publish_unread" do
let(:other_user) { Fabricate(:user) }
-
- before { Fabricate(:topic_user_watching, topic: topic, user: other_user) }
+ let!(:other_user_watching_topic) do
+ Fabricate(:topic_user_watching, topic: topic, user: other_user)
+ end
it "can correctly publish unread" do
message =
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index e2f20ebe154..1215e3fe0f4 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -1770,39 +1770,55 @@ RSpec.describe User do
end
describe "#new_user_posting_on_first_day?" do
- def create_test_user(opts = {})
- Fabricate(:user, { created_at: Time.zone.now }.merge(opts))
- end
-
it "is true for a user who has never posted" do
- expect(create_test_user.new_user_posting_on_first_day?).to eq(true)
+ expect(Fabricate(:user, created_at: Time.zone.now).new_user_posting_on_first_day?).to eq(true)
end
it "is false if the user is moderator or admin" do
- expect(create_test_user(moderator: true).new_user_posting_on_first_day?).to eq(false)
- expect(create_test_user(admin: true).new_user_posting_on_first_day?).to eq(false)
+ expect(
+ Fabricate(:user, created_at: Time.zone.now, moderator: true).new_user_posting_on_first_day?,
+ ).to eq(false)
+ expect(
+ Fabricate(:user, created_at: Time.zone.now, admin: true).new_user_posting_on_first_day?,
+ ).to eq(false)
end
it "is false for a user that is TL2 or above" do
- expect(create_test_user(trust_level: TrustLevel[2]).new_user_posting_on_first_day?).to eq(
- false,
- )
- expect(create_test_user(trust_level: TrustLevel[3]).new_user_posting_on_first_day?).to eq(
- false,
- )
- expect(create_test_user(trust_level: TrustLevel[0]).new_user_posting_on_first_day?).to eq(
- true,
- )
+ expect(
+ Fabricate(
+ :user,
+ created_at: Time.zone.now,
+ trust_level: TrustLevel[2],
+ ).new_user_posting_on_first_day?,
+ ).to eq(false)
+ expect(
+ Fabricate(
+ :user,
+ created_at: Time.zone.now,
+ trust_level: TrustLevel[3],
+ ).new_user_posting_on_first_day?,
+ ).to eq(false)
+ expect(
+ Fabricate(
+ :user,
+ created_at: Time.zone.now,
+ trust_level: TrustLevel[0],
+ ).new_user_posting_on_first_day?,
+ ).to eq(true)
end
it "is true for a TL1 user created less than 24 hours ago" do
- expect(create_test_user(trust_level: TrustLevel[1]).new_user_posting_on_first_day?).to eq(
- true,
- )
+ expect(
+ Fabricate(
+ :user,
+ created_at: Time.zone.now,
+ trust_level: TrustLevel[1],
+ ).new_user_posting_on_first_day?,
+ ).to eq(true)
end
it "is false if account was created more than 24 hours ago" do
- u = create_test_user(created_at: 25.hours.ago)
+ u = Fabricate(:user, created_at: 25.hours.ago)
expect(u.new_user_posting_on_first_day?).to eq(false)
end
end
diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb
index 0720191a82d..f871c9be177 100644
--- a/spec/rails_helper.rb
+++ b/spec/rails_helper.rb
@@ -61,6 +61,8 @@ require_relative "helpers/redis_snapshot_helper"
if ENV["LOAD_PLUGINS"] == "1"
Dir[Rails.root.join("plugins/*/spec/plugin_helper.rb")].each { |f| require f }
+ Dir[Rails.root.join("plugins/*/spec/support/**/*.rb")].sort.each { |f| require f }
+
Dir[Rails.root.join("plugins/*/spec/fabricators/**/*.rb")].each { |f| require f }
Dir[Rails.root.join("plugins/*/spec/system/page_objects/**/*.rb")].each { |f| require f }
diff --git a/spec/requests/onebox_controller_spec.rb b/spec/requests/onebox_controller_spec.rb
index 70124f7566b..534c7a5267b 100644
--- a/spec/requests/onebox_controller_spec.rb
+++ b/spec/requests/onebox_controller_spec.rb
@@ -42,23 +42,19 @@ RSpec.describe OneboxController do
html
end
- def bypass_limiting
- Oneboxer.onebox_previewed!(user.id)
- end
-
before { sign_in(user) }
it "invalidates the cache if refresh is passed" do
stub_request(:head, url)
stub_request(:get, url).to_return(status: 200, body: html).then.to_raise
- bypass_limiting
+ Oneboxer.onebox_previewed!(user.id)
Discourse.cache.delete("onebox__#{url}")
get "/onebox.json", params: { url: url }
expect(response.status).to eq(200)
expect(response.body).to include("Onebox1")
- bypass_limiting
+ Oneboxer.onebox_previewed!(user.id)
stub_request(:get, url).to_return(status: 200, body: html2).then.to_raise
get "/onebox.json", params: { url: url, refresh: "true" }
expect(response.status).to eq(200)
diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rb
index f74bbe9fc3d..33d58496ccb 100644
--- a/spec/requests/topics_controller_spec.rb
+++ b/spec/requests/topics_controller_spec.rb
@@ -2939,16 +2939,11 @@ RSpec.describe TopicsController do
end
describe "featured links" do
- def fabricate_topic(user, category = nil)
- topic = Fabricate(:topic, user: user, category: category)
- Fabricate(:post, user: post_author1, topic: topic)
- topic
- end
-
it "allows to update topic featured link" do
sign_in(trust_level_1)
- tl1_topic = fabricate_topic(trust_level_1)
+ tl1_topic = Fabricate(:topic, user: trust_level_1)
+ Fabricate(:post, user: post_author1, topic: tl1_topic)
put "/t/#{tl1_topic.slug}/#{tl1_topic.id}.json",
params: {
featured_link: "https://discourse.org",
@@ -2960,7 +2955,8 @@ RSpec.describe TopicsController do
it "doesn't allow TL0 users to update topic featured link" do
sign_in(trust_level_0)
- tl0_topic = fabricate_topic(trust_level_0)
+ tl0_topic = Fabricate(:topic, user: trust_level_0)
+ Fabricate(:post, user: post_author1, topic: tl0_topic)
put "/t/#{tl0_topic.slug}/#{tl0_topic.id}.json",
params: {
featured_link: "https://discourse.org",
@@ -2973,7 +2969,8 @@ RSpec.describe TopicsController do
sign_in(trust_level_1)
SiteSetting.topic_featured_link_enabled = false
- tl1_topic = fabricate_topic(trust_level_1)
+ tl1_topic = Fabricate(:topic, user: trust_level_1)
+ Fabricate(:post, user: post_author1, topic: tl1_topic)
put "/t/#{tl1_topic.slug}/#{tl1_topic.id}.json",
params: {
featured_link: "https://discourse.org",
@@ -2986,7 +2983,8 @@ RSpec.describe TopicsController do
sign_in(trust_level_1)
category = Fabricate(:category, topic_featured_link_allowed: false)
- tl1_topic_in_category = fabricate_topic(trust_level_1, category)
+ tl1_topic_in_category = Fabricate(:topic, user: trust_level_1, category:)
+ Fabricate(:post, user: post_author1, topic: tl1_topic_in_category)
put "/t/#{tl1_topic_in_category.slug}/#{tl1_topic_in_category.id}.json",
params: {
featured_link: "https://discourse.org",
diff --git a/spec/serializers/admin_user_list_serializer_spec.rb b/spec/serializers/admin_user_list_serializer_spec.rb
index 3703b99b4e1..96bdef39f90 100644
--- a/spec/serializers/admin_user_list_serializer_spec.rb
+++ b/spec/serializers/admin_user_list_serializer_spec.rb
@@ -8,7 +8,8 @@ RSpec.describe AdminUserListSerializer do
let(:serializer) { AdminUserListSerializer.new(user, scope: guardian, root: false) }
context "when totp enabled" do
- before { Fabricate(:user_second_factor_totp, user: user) }
+ fab!(:user_totp) { Fabricate(:user_second_factor_totp, user: user) }
+
it "returns the right values" do
json = serializer.as_json
@@ -17,7 +18,8 @@ RSpec.describe AdminUserListSerializer do
end
context "when security keys enabled" do
- before { Fabricate(:user_security_key, user: user) }
+ fab!(:user_security_key) { Fabricate(:user_security_key, user: user) }
+
it "returns the right values" do
json = serializer.as_json
@@ -26,84 +28,107 @@ RSpec.describe AdminUserListSerializer do
end
describe "emails" do
- fab!(:admin) { Fabricate(:user, admin: true, email: "[email protected]") }
- fab!(:moderator) { Fabricate(:user, moderator: true, email: "[email protected]") }
- fab!(:user) { Fabricate(:user, email: "[email protected]") }
-
- def serialize(user, viewed_by, opts = nil)
- AdminUserListSerializer.new(
- user,
+ subject(:json) do
+ described_class.new(
+ serialized_user,
scope: Guardian.new(viewed_by),
root: false,
- emails_desired: opts && opts[:emails_desired],
+ emails_desired: emails_desired,
).as_json
end
- def fabricate_secondary_emails_for(u)
- Fabricate(:secondary_email, user: u, email: "[email protected]")
- Fabricate(:secondary_email, user: u, email: "[email protected]")
- end
+ fab!(:admin) { Fabricate(:user, admin: true, email: "[email protected]") }
+ fab!(:moderator) { Fabricate(:user, moderator: true, email: "[email protected]") }
+ fab!(:user) { Fabricate(:user, email: "[email protected]") }
- it "contains an admin's own emails" do
- fabricate_secondary_emails_for(admin)
- json = serialize(admin, admin)
- expect(json[:email]).to eq("[email protected]")
- expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ let(:serialized_user) { user }
+ let(:viewed_by) { user }
+ let(:emails_desired) { nil }
+ let!(:secondary_emails) do
+ %w[first second].map do |name|
+ Fabricate(:secondary_email, user: serialized_user, email: "#{name}@email.com")
+ end
end
- it "doesn't include a regular user's emails" do
- fabricate_secondary_emails_for(user)
- json = serialize(user, user)
- expect(json[:email]).to eq(nil)
- expect(json[:secondary_emails]).to eq(nil)
+ context "when an admin views their own account" do
+ let(:serialized_user) { admin }
+ let(:viewed_by) { admin }
+
+ it "contains the admin's emails" do
+ expect(json[:email]).to eq("[email protected]")
+ expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ end
end
- it "doesn't return emails for a moderator request when moderators_view_emails is disabled" do
- SiteSetting.moderators_view_emails = false
- fabricate_secondary_emails_for(user)
- json = serialize(user, moderator, emails_desired: true)
- expect(json[:email]).to eq(nil)
- expect(json[:secondary_emails]).to eq(nil)
+ context "when a regular user views their own account" do
+ it "doesn't include the user's emails" do
+ expect(json[:email]).to eq(nil)
+ expect(json[:secondary_emails]).to eq(nil)
+ end
end
- it "returns emails for a moderator request when moderators_view_emails is enabled" do
- SiteSetting.moderators_view_emails = true
- fabricate_secondary_emails_for(user)
- json = serialize(user, moderator, emails_desired: true)
- expect(json[:email]).to eq("[email protected]")
- expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ context "when a moderator requests a user's emails" do
+ let(:viewed_by) { moderator }
+ let(:emails_desired) { true }
+
+ it "doesn't return emails when moderators_view_emails is disabled" do
+ SiteSetting.moderators_view_emails = false
+
+ expect(json[:email]).to eq(nil)
+ expect(json[:secondary_emails]).to eq(nil)
+ end
+
+ it "returns emails when moderators_view_emails is enabled" do
+ SiteSetting.moderators_view_emails = true
+
+ expect(json[:email]).to eq("[email protected]")
+ expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ end
end
- it "returns emails for admins when emails_desired is true" do
- fabricate_secondary_emails_for(user)
- json = serialize(user, admin, emails_desired: true)
- expect(json[:email]).to eq("[email protected]")
- expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ context "when an admin requests a user's emails" do
+ let(:viewed_by) { admin }
+ let(:emails_desired) { true }
+
+ it "returns the emails" do
+ expect(json[:email]).to eq("[email protected]")
+ expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ end
end
- it "returns a staged user's emails to admins" do
- user.update!(staged: true)
- fabricate_secondary_emails_for(user)
- json = serialize(user, admin)
- expect(json[:email]).to eq("[email protected]")
- expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ context "when an admin views a staged user" do
+ let(:viewed_by) { admin }
+
+ it "returns the user's emails" do
+ user.update!(staged: true)
+
+ expect(json[:email]).to eq("[email protected]")
+ expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ end
end
- it "doesn't return a staged user's emails to moderators when disabled" do
- SiteSetting.moderators_view_emails = false
- user.update!(staged: true)
- fabricate_secondary_emails_for(user)
- json = serialize(user, moderator)
- expect(json[:email]).to eq(nil)
- expect(json[:secondary_emails]).to eq(nil)
+ context "when a moderator views a staged user" do
+ let(:viewed_by) { moderator }
+
+ it "doesn't return the user's emails when moderator email access is disabled" do
+ SiteSetting.moderators_view_emails = false
+ user.update!(staged: true)
+
+ expect(json[:email]).to eq(nil)
+ expect(json[:secondary_emails]).to eq(nil)
+ end
end
- it "returns a staged user's emails for admins when emails_desired is true" do
- user.update!(staged: true)
- fabricate_secondary_emails_for(user)
- json = serialize(user, admin, emails_desired: true)
- expect(json[:email]).to eq("[email protected]")
- expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ context "when an admin requests a staged user's emails" do
+ let(:viewed_by) { admin }
+ let(:emails_desired) { true }
+
+ it "returns the user's emails" do
+ user.update!(staged: true)
+
+ expect(json[:email]).to eq("[email protected]")
+ expect(json[:secondary_emails]).to contain_exactly("[email protected]", "[email protected]")
+ end
end
end
diff --git a/spec/serializers/post_serializer_spec.rb b/spec/serializers/post_serializer_spec.rb
index d3f8d771b65..6dd3a157001 100644
--- a/spec/serializers/post_serializer_spec.rb
+++ b/spec/serializers/post_serializer_spec.rb
@@ -159,20 +159,21 @@ RSpec.describe PostSerializer do
end
context "with a post by a suspended user" do
- def serializer
- PostSerializer.new(post, scope: Guardian.new(Fabricate(:admin)), root: false).as_json
- end
+ fab!(:admin)
it "serializes correctly" do
- expect(serializer[:user_suspended]).to be_nil
+ serialized_post = described_class.new(post, scope: Guardian.new(admin), root: false).as_json
+ expect(serialized_post[:user_suspended]).to be_nil
post.user.update!(suspended_till: 1.month.from_now)
- expect(serializer[:user_suspended]).to eq(true)
+ serialized_post = described_class.new(post, scope: Guardian.new(admin), root: false).as_json
+ expect(serialized_post[:user_suspended]).to eq(true)
freeze_time(2.months.from_now)
- expect(serializer[:user_suspended]).to be_nil
+ serialized_post = described_class.new(post, scope: Guardian.new(admin), root: false).as_json
+ expect(serialized_post[:user_suspended]).to be_nil
end
end
@@ -591,19 +592,19 @@ RSpec.describe PostSerializer do
end
describe "#user_status" do
+ subject(:serialized_user_status) do
+ described_class.new(post, scope: Guardian.new(user), root: false).as_json[:user_status]
+ end
+
fab!(:user_status)
fab!(:user) { Fabricate(:user, user_status:) }
fab!(:post) { Fabricate(:post, user:) }
- def serialize_user_status(scope: Guardian.new(user))
- described_class.new(post, scope:, root: false).as_json[:user_status]
- end
-
context "when user status is disabled" do
before { SiteSetting.enable_user_status = false }
it "doesn't include status" do
- expect(serialize_user_status).to be_nil
+ expect(serialized_user_status).to be_nil
end
end
@@ -611,13 +612,13 @@ RSpec.describe PostSerializer do
before { SiteSetting.enable_user_status = true }
it "includes status" do
- expect(serialize_user_status).to be_present
+ expect(serialized_user_status).to be_present
end
it "doesn't include status if user doesn't have it set" do
user.clear_status!
user.reload
- expect(serialize_user_status).to be_nil
+ expect(serialized_user_status).to be_nil
end
it "doesn't include status for a public topic author with a hidden profile" do
@@ -633,7 +634,7 @@ RSpec.describe PostSerializer do
it "respects guardian's can_see_user_status?" do
user.update!(silenced_till: 1.year.from_now)
scope = Guardian.new(Fabricate(:user))
- expect(serialize_user_status(scope:)).to be_nil
+ expect(described_class.new(post, scope:, root: false).as_json[:user_status]).to be_nil
end
end
end
@@ -1004,11 +1005,11 @@ RSpec.describe PostSerializer do
fab!(:author, :user)
fab!(:author_post) { Fabricate(:post, user: author) }
fab!(:group)
+ fab!(:post_localization) { Fabricate(:post_localization, post: author_post, locale: "ja") }
before do
SiteSetting.content_localization_enabled = true
SiteSetting.content_localization_allowed_groups = group.id.to_s
- Fabricate(:post_localization, post: author_post, locale: "ja")
end
it "is included for users in allowed groups" do
@@ -1041,11 +1042,15 @@ RSpec.describe PostSerializer do
fab!(:linked_post) do
Fabricate(:post, topic: linked_topic, post_number: 1, locale: "en", raw: "Subdue the enemy.")
end
+ fab!(:topic_localization) do
+ Fabricate(:topic_localization, topic: linked_topic, locale: "ja", title: "孫子の兵法")
+ end
+ fab!(:post_localization) do
+ Fabricate(:post_localization, post: linked_post, locale: "ja", cooked: "<p>戦わずして勝つ</p>")
+ end
before do
SiteSetting.content_localization_enabled = true
- Fabricate(:topic_localization, topic: linked_topic, locale: "ja", title: "孫子の兵法")
- Fabricate(:post_localization, post: linked_post, locale: "ja", cooked: "<p>戦わずして勝つ</p>")
TopicLink.create!(
topic: source_topic,
post: source_post,
diff --git a/spec/serializers/sidebar_section_serializer_spec.rb b/spec/serializers/sidebar_section_serializer_spec.rb
index e07c5acbb8e..5b84a7050d4 100644
--- a/spec/serializers/sidebar_section_serializer_spec.rb
+++ b/spec/serializers/sidebar_section_serializer_spec.rb
@@ -7,27 +7,32 @@ describe SidebarSectionSerializer do
Fabricate(:sidebar_section, title: "Participate", public: true, locale: "en")
end
fab!(:sidebar_url) { Fabricate(:sidebar_url, name: "Welcome", value: "/welcome", locale: "en") }
-
- before do
+ fab!(:sidebar_section_link) do
Fabricate(:sidebar_section_link, sidebar_section:, linkable: sidebar_url)
+ end
+ fab!(:sidebar_section_localization) do
Fabricate(:sidebar_section_localization, sidebar_section:, locale: "ja", title: "参加")
+ end
+ fab!(:sidebar_url_localization) do
Fabricate(:sidebar_url_localization, sidebar_url:, locale: "ja", name: "ようこそ")
end
- def serialized_for(guardian)
- reloaded =
- SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(sidebar_section.id)
- described_class.new(reloaded, scope: guardian, root: false).as_json
+ let(:reloaded_section) do
+ SidebarSection.includes(:localizations, sidebar_urls: :localizations).find(sidebar_section.id)
+ end
+ let(:serialized_for_user) do
+ described_class.new(reloaded_section, scope: Guardian.new(user), root: false).as_json
+ end
+ let(:serialized_for_admin) do
+ described_class.new(reloaded_section, scope: Guardian.new(admin), root: false).as_json
end
it "returns localized section titles and link names when content localization is enabled" do
SiteSetting.content_localization_enabled = true
I18n.with_locale("ja") do
- json = serialized_for(Guardian.new(user))
-
- expect(json[:title]).to eq("参加")
- expect(json[:links].first[:name]).to eq("ようこそ")
+ expect(serialized_for_user[:title]).to eq("参加")
+ expect(serialized_for_user[:links].first[:name]).to eq("ようこそ")
end
end
@@ -35,20 +40,18 @@ describe SidebarSectionSerializer do
SiteSetting.content_localization_enabled = false
I18n.with_locale("ja") do
- json = serialized_for(Guardian.new(user))
-
- expect(json[:title]).to eq("Participate")
- expect(json[:links].first[:name]).to eq("Welcome")
+ expect(serialized_for_user[:title]).to eq("Participate")
+ expect(serialized_for_user[:links].first[:name]).to eq("Welcome")
end
end
it "does not expose localization rows in the regular presentation payload" do
SiteSetting.content_localization_enabled = true
- expect(serialized_for(Guardian.new(user))[:localizations]).to eq(nil)
- expect(serialized_for(Guardian.new(user))[:links].first[:localizations]).to eq(nil)
- expect(serialized_for(Guardian.new(admin))[:localizations]).to eq(nil)
- expect(serialized_for(Guardian.new(admin))[:links].first[:localizations]).to eq(nil)
+ expect(serialized_for_user[:localizations]).to eq(nil)
+ expect(serialized_for_user[:links].first[:localizations]).to eq(nil)
+ expect(serialized_for_admin[:localizations]).to eq(nil)
+ expect(serialized_for_admin[:links].first[:localizations]).to eq(nil)
end
it "returns source labels and localization rows from the edit serializer" do
diff --git a/spec/services/notification_emailer_spec.rb b/spec/services/notification_emailer_spec.rb
index a91660dff56..a46e6f39570 100644
--- a/spec/services/notification_emailer_spec.rb
+++ b/spec/services/notification_emailer_spec.rb
@@ -9,13 +9,12 @@ RSpec.describe NotificationEmailer do
fab!(:topic)
fab!(:post) { Fabricate(:post, topic: topic) }
- # something is off with fabricator
- def create_notification(type, user = nil)
- user ||= Fabricate(:user)
+ let(:notification_user) { Fabricate(:user) }
+ let(:notification) do
Notification.create(
data: "{\"a\": 1}",
- user: user,
- notification_type: Notification.types[type],
+ user: notification_user,
+ notification_type: Notification.types[notification_kind],
topic: topic,
post_number: post.post_number,
skip_send_email: true,
@@ -144,7 +143,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_mentioned }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:mentioned) }
+ let(:notification_kind) { :mentioned }
include_examples "enqueue_public"
@@ -163,7 +162,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_replied }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:replied) }
+ let(:notification_kind) { :replied }
include_examples "enqueue_public"
end
@@ -172,7 +171,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_quoted }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:quoted) }
+ let(:notification_kind) { :quoted }
include_examples "enqueue_public"
end
@@ -181,7 +180,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_linked }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:linked) }
+ let(:notification_kind) { :linked }
include_examples "enqueue_public"
end
@@ -190,7 +189,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_posted }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:posted) }
+ let(:notification_kind) { :posted }
include_examples "enqueue_public"
end
@@ -199,7 +198,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_posted }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:watching_category_or_tag) }
+ let(:notification_kind) { :watching_category_or_tag }
include_examples "enqueue_public"
end
@@ -208,7 +207,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_private_message }
let(:delay) { SiteSetting.personal_email_time_window_seconds }
- let!(:notification) { create_notification(:private_message) }
+ let(:notification_kind) { :private_message }
include_examples "enqueue_private"
@@ -225,7 +224,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_invited_to_private_message }
let(:delay) { SiteSetting.personal_email_time_window_seconds }
- let!(:notification) { create_notification(:invited_to_private_message) }
+ let(:notification_kind) { :invited_to_private_message }
include_examples "enqueue_public"
end
@@ -234,7 +233,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_invited_to_topic }
let(:delay) { SiteSetting.personal_email_time_window_seconds }
- let!(:notification) { create_notification(:invited_to_topic) }
+ let(:notification_kind) { :invited_to_topic }
include_examples "enqueue_public"
end
@@ -243,7 +242,7 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :user_watching_first_post }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:watching_first_post) }
+ let(:notification_kind) { :watching_first_post }
include_examples "enqueue_public"
end
@@ -252,14 +251,22 @@ RSpec.describe NotificationEmailer do
let(:no_delay) { no_delay }
let(:type) { :post_approved }
let(:delay) { SiteSetting.email_time_window_mins.minutes }
- let!(:notification) { create_notification(:post_approved) }
+ let(:notification_kind) { :post_approved }
include_examples "enqueue_public"
end
end
it "has translations for each sendable notification type" do
- notification = create_notification(:mentioned)
+ notification =
+ Notification.create(
+ data: "{\"a\": 1}",
+ user: Fabricate(:user),
+ notification_type: Notification.types[:mentioned],
+ topic: topic,
+ post_number: post.post_number,
+ skip_send_email: true,
+ )
email_user = NotificationEmailer::EmailUser.new(notification, no_delay: true)
subkeys = %w[title subject_template text_body_template]
@@ -290,7 +297,7 @@ RSpec.describe NotificationEmailer do
describe "with plugin-added email_notification_filters" do
let!(:plugin) { Plugin::Instance.new }
- let!(:notification) { create_notification(:quoted) }
+ let(:notification_kind) { :quoted }
let(:no_delay) { true }
let(:type) { :user_quoted }
@@ -319,8 +326,23 @@ RSpec.describe NotificationEmailer do
context "when notification is mentioned or group_mentioned type" do
it "doesn't enqueue the job to send user email" do
staged_user = Fabricate(:staged)
- mentioned = create_notification(:mentioned, staged_user)
- group_mentioned = create_notification(:group_mentioned, staged_user)
+ notification_attributes = {
+ data: "{\"a\": 1}",
+ user: staged_user,
+ topic: topic,
+ post_number: post.post_number,
+ skip_send_email: true,
+ }
+ mentioned =
+ Notification.create(
+ **notification_attributes,
+ notification_type: Notification.types[:mentioned],
+ )
+ group_mentioned =
+ Notification.create(
+ **notification_attributes,
+ notification_type: Notification.types[:group_mentioned],
+ )
expect_not_enqueued_with(job: :user_email) do
NotificationEmailer.process_notification(mentioned, no_delay: Time.zone.now)
diff --git a/spec/services/notifications/consolidate_notifications_spec.rb b/spec/services/notifications/consolidate_notifications_spec.rb
index 712a642013c..a27a169d8d5 100644
--- a/spec/services/notifications/consolidate_notifications_spec.rb
+++ b/spec/services/notifications/consolidate_notifications_spec.rb
@@ -13,6 +13,16 @@ RSpec.describe Notifications::ConsolidateNotifications do
threshold: 1,
).set_mutations(set_data_blk: Proc.new { |n| n.data_hash.merge(consolidated: true) })
end
+ let(:like_notifications) do
+ Array.new(3) do
+ Fabricate.build(
+ :notification,
+ user: user,
+ notification_type: Notification.types[:liked],
+ data: {}.to_json,
+ )
+ end
+ end
it "applies a callback when consolidating a notification" do
rule.before_consolidation_callbacks(
@@ -20,8 +30,8 @@ RSpec.describe Notifications::ConsolidateNotifications do
Proc.new { |_, data| data[:consolidation_callback_called] = true },
)
- rule.consolidate_or_save!(build_like_notification)
- rule.consolidate_or_save!(build_like_notification)
+ rule.consolidate_or_save!(like_notifications[0])
+ rule.consolidate_or_save!(like_notifications[1])
consolidated_notification = Notification.where(user: user).last
@@ -33,27 +43,18 @@ RSpec.describe Notifications::ConsolidateNotifications do
before_update_blk: Proc.new { |_, data| data[:update_callback_called] = true },
)
- rule.consolidate_or_save!(build_like_notification)
- rule.consolidate_or_save!(build_like_notification)
+ rule.consolidate_or_save!(like_notifications[0])
+ rule.consolidate_or_save!(like_notifications[1])
consolidated_notification = Notification.where(user: user).last
expect(consolidated_notification.data_hash[:update_callback_called]).to be_nil
- rule.consolidate_or_save!(build_like_notification)
+ rule.consolidate_or_save!(like_notifications[2])
consolidated_notification = Notification.where(user: user).last
expect(consolidated_notification.data_hash[:update_callback_called]).to eq(true)
end
-
- def build_like_notification
- Fabricate.build(
- :notification,
- user: user,
- notification_type: Notification.types[:liked],
- data: {}.to_json,
- )
- end
end
end
diff --git a/spec/services/notifications/consolidation_planner_spec.rb b/spec/services/notifications/consolidation_planner_spec.rb
index ae126eaaee1..d59673e495b 100644
--- a/spec/services/notifications/consolidation_planner_spec.rb
+++ b/spec/services/notifications/consolidation_planner_spec.rb
@@ -8,22 +8,34 @@ RSpec.describe Notifications::ConsolidationPlanner do
fab!(:user)
let(:like_user) { "user1" }
let(:link_user) { "user2" }
+ let(:like_notification) do
+ Fabricate.build(
+ :notification,
+ user: user,
+ notification_type: Notification.types[:liked],
+ data: { display_username: like_user }.to_json,
+ )
+ end
+ let(:link_notification) do
+ Fabricate.build(
+ :notification,
+ user: user,
+ notification_type: Notification.types[:linked],
+ data: { display_username: link_user }.to_json,
+ )
+ end
before { SiteSetting.notification_consolidation_threshold = threshold }
it "does nothing when it hasn't passed the consolidation threshold yet for likes" do
- notification = build_notification(:liked, { display_username: like_user })
-
- saved_like = planner.consolidate_or_save!(notification)
+ saved_like = planner.consolidate_or_save!(like_notification)
expect(saved_like.id).to be_present
expect(saved_like.notification_type).to eq(Notification.types[:liked])
end
it "does nothing when it hasn't passed the consolidation threshold yet for links" do
- notification = build_notification(:linked, { display_username: link_user })
-
- saved_link = planner.consolidate_or_save!(notification)
+ saved_link = planner.consolidate_or_save!(link_notification)
expect(saved_link.id).to be_present
expect(saved_link.notification_type).to eq(Notification.types[:linked])
@@ -37,9 +49,7 @@ RSpec.describe Notifications::ConsolidationPlanner do
notification_type: Notification.types[:liked],
data: { display_username: like_user }.to_json,
)
- notification = build_notification(:liked, { display_username: like_user })
-
- consolidated_like = planner.consolidate_or_save!(notification)
+ consolidated_like = planner.consolidate_or_save!(like_notification)
expect(consolidated_like.id).not_to eq(first_notification.id)
expect(consolidated_like.notification_type).to eq(Notification.types[:liked_consolidated])
@@ -55,9 +65,7 @@ RSpec.describe Notifications::ConsolidationPlanner do
notification_type: Notification.types[:linked],
data: { display_username: link_user }.to_json,
)
- notification = build_notification(:linked, { display_username: link_user })
-
- consolidated_link = planner.consolidate_or_save!(notification)
+ consolidated_link = planner.consolidate_or_save!(link_notification)
expect(consolidated_link.id).not_to eq(first_notification.id)
expect(consolidated_link.notification_type).to eq(Notification.types[:linked_consolidated])
@@ -73,11 +81,9 @@ RSpec.describe Notifications::ConsolidationPlanner do
notification_type: Notification.types[:liked_consolidated],
data: { count: count, display_username: like_user }.to_json,
)
- notification = build_notification(:liked, { display_username: like_user })
+ updated = planner.consolidate_or_save!(like_notification)
- updated = planner.consolidate_or_save!(notification)
-
- expect { notification.reload }.to raise_error(ActiveRecord::RecordNotFound)
+ expect { like_notification.reload }.to raise_error(ActiveRecord::RecordNotFound)
data = JSON.parse(updated.data)
expect(data["count"]).to eq(count + 1)
end
@@ -90,26 +96,11 @@ RSpec.describe Notifications::ConsolidationPlanner do
notification_type: Notification.types[:linked_consolidated],
data: { count: count, display_username: link_user }.to_json,
)
- notification = build_notification(:linked, { display_username: link_user })
-
- updated = planner.consolidate_or_save!(notification)
+ updated = planner.consolidate_or_save!(link_notification)
- expect { notification.reload }.to raise_error(ActiveRecord::RecordNotFound)
+ expect { link_notification.reload }.to raise_error(ActiveRecord::RecordNotFound)
data = JSON.parse(updated.data)
expect(data["count"]).to eq(count + 1)
end
end
-
- def build_notification(type_sym, data)
- Fabricate.build(
- :notification,
- user: user,
- notification_type: Notification.types[type_sym],
- data: data.to_json,
- )
- end
-
- def plan_for(notification)
- planner.plan_for(notification)
- end
end
diff --git a/spec/services/problem_check/out_of_date_themes_spec.rb b/spec/services/problem_check/out_of_date_themes_spec.rb
index 4e91a045134..39ea051db11 100644
--- a/spec/services/problem_check/out_of_date_themes_spec.rb
+++ b/spec/services/problem_check/out_of_date_themes_spec.rb
@@ -11,7 +11,7 @@ RSpec.describe ProblemCheck::OutOfDateThemes do
)
end
- before { Fabricate(:theme, id: 44, remote_theme: remote, name: "Test< Theme") }
+ let!(:theme) { Fabricate(:theme, id: 44, remote_theme: remote, name: "Test< Theme") }
context "when theme is out of date" do
let(:commits_behind) { 2 }
diff --git a/spec/services/problem_check/translation_overrides_spec.rb b/spec/services/problem_check/translation_overrides_spec.rb
index e3efdba75aa..e15aeafaa61 100644
--- a/spec/services/problem_check/translation_overrides_spec.rb
+++ b/spec/services/problem_check/translation_overrides_spec.rb
@@ -6,7 +6,7 @@ RSpec.describe ProblemCheck::TranslationOverrides do
around { |example| allow_missing_translations(&example) }
describe ".call" do
- before { Fabricate(:translation_override, status: status) }
+ let!(:translation_override) { Fabricate(:translation_override, status: status) }
context "when there are outdated translation overrides" do
let(:status) { "outdated" }
diff --git a/spec/services/problem_check/unreachable_themes_spec.rb b/spec/services/problem_check/unreachable_themes_spec.rb
index 089661aab3a..75923d8dbd6 100644
--- a/spec/services/problem_check/unreachable_themes_spec.rb
+++ b/spec/services/problem_check/unreachable_themes_spec.rb
@@ -11,7 +11,7 @@ RSpec.describe ProblemCheck::UnreachableThemes do
)
end
- before { Fabricate(:theme, id: 50, remote_theme: remote, name: "Test Theme") }
+ let!(:theme) { Fabricate(:theme, id: 50, remote_theme: remote, name: "Test Theme") }
context "when theme is unreachable" do
let(:last_error) { "Can't reach. Too short." }
diff --git a/spec/services/sidebar_section_updater_spec.rb b/spec/services/sidebar_section_updater_spec.rb
index 4b683d24dbd..ca1a64c447f 100644
--- a/spec/services/sidebar_section_updater_spec.rb
+++ b/spec/services/sidebar_section_updater_spec.rb
@@ -5,9 +5,10 @@ describe SidebarSectionUpdater do
fab!(:sidebar_section) { Fabricate(:sidebar_section, public: true) }
fab!(:first_url) { Fabricate(:sidebar_url, name: "First", value: "/first") }
fab!(:second_url) { Fabricate(:sidebar_url, name: "Second", value: "/second") }
-
- before do
+ fab!(:first_section_link) do
Fabricate(:sidebar_section_link, sidebar_section:, linkable: first_url, position: 0)
+ end
+ fab!(:second_section_link) do
Fabricate(:sidebar_section_link, sidebar_section:, linkable: second_url, position: 1)
end
diff --git a/spec/services/upcoming_changes/action/track_added_changes_spec.rb b/spec/services/upcoming_changes/action/track_added_changes_spec.rb
index 41a763feaa2..b45d17f395a 100644
--- a/spec/services/upcoming_changes/action/track_added_changes_spec.rb
+++ b/spec/services/upcoming_changes/action/track_added_changes_spec.rb
@@ -1,6 +1,12 @@
# frozen_string_literal: true
RSpec.describe UpcomingChanges::Action::TrackAddedChanges do
+ let(:scoped_events) do
+ UpcomingChangeEvent.where(
+ upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars],
+ )
+ end
+
before do
mock_upcoming_change_metadata(
{
@@ -20,12 +26,6 @@ RSpec.describe UpcomingChanges::Action::TrackAddedChanges do
)
end
- def scoped_events
- UpcomingChangeEvent.where(
- upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars],
- )
- end
-
fab!(:admin_1, :admin)
fab!(:admin_2, :admin)
diff --git a/spec/services/upcoming_changes/action/track_removed_changes_spec.rb b/spec/services/upcoming_changes/action/track_removed_changes_spec.rb
index 788c751c92c..c2d1e9dd1da 100644
--- a/spec/services/upcoming_changes/action/track_removed_changes_spec.rb
+++ b/spec/services/upcoming_changes/action/track_removed_changes_spec.rb
@@ -1,6 +1,12 @@
# frozen_string_literal: true
RSpec.describe UpcomingChanges::Action::TrackRemovedChanges do
+ let(:scoped_events) do
+ UpcomingChangeEvent.where(
+ upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars old_removed_change],
+ )
+ end
+
before do
mock_upcoming_change_metadata(
{
@@ -20,12 +26,6 @@ RSpec.describe UpcomingChanges::Action::TrackRemovedChanges do
)
end
- def scoped_events
- UpcomingChangeEvent.where(
- upcoming_change_name: %i[enable_upload_debug_mode show_user_menu_avatars old_removed_change],
- )
- end
-
describe ".call" do
subject(:result) { described_class.call }
diff --git a/spec/support/discourse_workflows_data_table_helpers.rb b/spec/support/discourse_workflows_data_table_helpers.rb
deleted file mode 100644
index 61d79b1b7e1..00000000000
--- a/spec/support/discourse_workflows_data_table_helpers.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-# frozen_string_literal: true
-
-module DataTableHelpers
- def data_table_facade(data_table)
- DiscourseWorkflows::DataTables::Facade.new(data_table.reload)
- end
-
- def insert_data_table_row(data_table, data = {})
- dt = data_table.reload
- facade = DiscourseWorkflows::DataTables::Facade.new(dt)
- facade.insert(facade.build_row_input(data: data, fill_missing: true))
- end
-
- def list_data_table_rows(data_table, **options)
- facade = data_table_facade(data_table)
- query =
- facade.build_query(
- filter: options[:normalized_filter],
- limit: options[:limit],
- offset: options[:offset],
- sort_by: options[:sort_by],
- sort_direction: options[:sort_direction],
- optional_filter: true,
- )
-
- facade.query(query)
- end
-
- def count_data_table_rows(data_table, normalized_filter: nil)
- facade = data_table_facade(data_table)
- query = facade.build_query(filter: normalized_filter, optional_filter: true)
- facade.count(query)
- end
-
- def find_data_table_row(data_table, row_id)
- data_table_facade(data_table).find_row(row_id)
- end
-end
-
-RSpec.configure { |config| config.include(DataTableHelpers) }
diff --git a/spec/tasks/migrate_discourse_gifs_to_core_spec.rb b/spec/tasks/migrate_discourse_gifs_to_core_spec.rb
index 171e84f82a8..67dc9c4e44d 100644
--- a/spec/tasks/migrate_discourse_gifs_to_core_spec.rb
+++ b/spec/tasks/migrate_discourse_gifs_to_core_spec.rb
@@ -93,9 +93,7 @@ RSpec.describe "tasks/migrate_discourse_gifs_to_core" do
end
def run_migration(theme, enable_gifs: false)
- expect {
- DiscourseGifsMigration.migrate_component(theme, enable_gifs: enable_gifs)
- }.to output.to_stdout
+ expect { DiscourseGifsMigration.migrate_component(theme, enable_gifs:) }.to output.to_stdout
end
describe ".find_component_in_db" do
@@ -334,14 +332,20 @@ RSpec.describe "tasks/migrate_discourse_gifs_to_core" do
end
context "with theme translation overrides" do
- def add_translation_override(theme, key, value, locale: "en")
- ThemeTranslationOverride.create!(theme:, locale:, translation_key: key, value:)
- end
-
it "migrates customised strings (per locale) to the matching core site text",
:aggregate_failures do
- add_translation_override(component, "gif.composer_title", "Add a GIF")
- add_translation_override(component, "gif.modal_title", "Chercher des GIFs", locale: "fr")
+ ThemeTranslationOverride.create!(
+ theme: component,
+ locale: "en",
+ translation_key: "gif.composer_title",
+ value: "Add a GIF",
+ )
+ ThemeTranslationOverride.create!(
+ theme: component,
+ locale: "fr",
+ translation_key: "gif.modal_title",
+ value: "Chercher des GIFs",
+ )
run_migration(component)
@@ -357,7 +361,12 @@ RSpec.describe "tasks/migrate_discourse_gifs_to_core" do
end
it "skips overrides of keys with no core equivalent" do
- add_translation_override(component, "gif.query", "Keyword")
+ ThemeTranslationOverride.create!(
+ theme: component,
+ locale: "en",
+ translation_key: "gif.query",
+ value: "Keyword",
+ )
run_migration(component)
@@ -401,9 +410,7 @@ RSpec.describe "tasks/migrate_discourse_gifs_to_core" do
end
describe "the themes:discourse_gifs:migrate task" do
- def run_task
- capture_stdout { Rake::Task["themes:discourse_gifs:migrate"].invoke }
- end
+ subject(:run_task) { capture_stdout { Rake::Task["themes:discourse_gifs:migrate"].invoke } }
before { allow(DiscourseGifsMigration).to receive(:migrate_all) }