A platform for community discussion. Free, open, simple.
DEV: Improve RSpec agent testing guidance (#41611)
Alan Guo Xiang Tand4ebfad68b38
diff --git a/.skills/discourse-writing-rspec-tests/SKILL.md b/.skills/discourse-writing-rspec-tests/SKILL.mdindex 77c73e2e9f8..17903c89fbd 100644--- a/.skills/discourse-writing-rspec-tests/SKILL.md+++ b/.skills/discourse-writing-rspec-tests/SKILL.md@@ -10,16 +10,18 @@ Discourse uses RSpec for testing. Follow these patterns for all test types.## Testing Principles- **Test behavior, not implementation** — test public interfaces; don't assert on internal state or private methods. Refactoring internals shouldn't break tests.+- **Choose assertions at the public boundary** — for a query, assert its return value. For a command, drive its public entry point and assert the direct side effect it owns: persisted state, an enqueued job, an emitted event, a response body, or rendered output. Group class, service, job, and model specs by that entry point (`describe ".call"`, `describe "#execute"`, or `describe "#expire!"`).- **One concept per test** — each `it` block verifies one behavior for clear failure diagnosis.- **Don't over-mock** — mock external boundaries (HTTP, third-party services), not internal collaborators. Too many mocks signals a design problem.- **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.- **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.- **Arrange-Act-Assert** — clear separation of setup, action, and verification in each test.- **Don't test framework behavior** — don't test that Rails validations work; test your business logic.-- **Avoid redundant multi-layer testing** — if a model spec tests a validation, the controller spec doesn't need to re-verify that same validation logic.+- **Each layer asserts what it owns** — models own validations, scopes, callbacks, and persisted state; services own orchestration, authorization, and return values; request specs own the HTTP contract and externally visible effects of the action; jobs own execution behavior and any required idempotency. Don't re-assert a lower layer's contract from above. Test callbacks through the public operation that invokes them, not with a group such as `describe "after_commit :callback_name"`.- **No single-letter block variables** — use descriptive names like `|vote|`, `|option|`, not `|v|`, `|o|`.- **Assert collections in a single assertion** — use `contain_exactly` or `eq` instead of multiple `include`/`not_to include` checks.- **Reference objects, not literal strings, in negative assertions** — `expect(response.body).not_to include("hidden data explorer excerpt")` silently passes if the literal has a typo or drifts from the source, giving a false sense of security. Reference the object directly (`expect(response.body).not_to include(private_post.raw)`) so the assertion stays in sync with the data under test. The same applies to any `not_to include`/`not_to match` against hardcoded strings.@@ -27,10 +29,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.-## Style Guide Reference--Before writing any RSpec code, read [references/rspec-style-guide.md](references/rspec-style-guide.md) and apply those conventions alongside the Discourse-specific patterns below.-## Test Data with FabricatorsUse `fab!` for shared test data, or `Fabricate` inline within the test example:@@ -54,6 +52,8 @@ endNever 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 EfficiencyTests have setup overhead. **Optimize for the fewest test examples possible:**@@ -61,6 +61,7 @@ Tests have setup overhead. **Optimize for the fewest test examples possible:**- Combine related assertions in a single `it` block when testing the same page/state- Avoid separate tests for trivial variations- Each `it` block incurs setup overhead; batch checks where logical+- Use one system test per user flow, not per internal code path. If scenarios look the same to the user but differ internally, test the flow once and cover the branches with cheaper tests.## Running Testsdiff --git a/.skills/discourse-writing-rspec-tests/references/request-specs.md b/.skills/discourse-writing-rspec-tests/references/request-specs.mdindex dc356e1ba10..4a5bdc18a11 100644--- a/.skills/discourse-writing-rspec-tests/references/request-specs.md+++ b/.skills/discourse-writing-rspec-tests/references/request-specs.md@@ -34,7 +34,7 @@ describe "#destroy" doend```-The `#` prefix follows the instance-method convention from the [RSpec style guide](rspec-style-guide.md). Each action's describe block is the home for all scenarios that hit that action — signed-in vs anonymous, permission variations, parameter variations, etc.+The `#` prefix identifies an instance method. Each action's describe block is the home for all scenarios that hit that action — signed-in vs anonymous, permission variations, parameter variations, etc.Reserve bare descriptive strings (`describe "extensibility event"`) for cross-cutting concerns that don't map to a single action.diff --git a/.skills/discourse-writing-rspec-tests/references/rspec-style-guide.md b/.skills/discourse-writing-rspec-tests/references/rspec-style-guide.mddeleted file mode 100644index af8e6609009..00000000000--- a/.skills/discourse-writing-rspec-tests/references/rspec-style-guide.md+++ /dev/null@@ -1,90 +0,0 @@-# RSpec Style Guide--> Adapted from: https://rspec.rubystyle.guide/--## Layout--- **No blank lines** immediately after `feature`, `context`, or `describe` declarations-- **One blank line** between separate `describe`/`context` blocks; no blank line before closing `end`-- **One blank line** after `let`, `subject`, and `before`/`after` declarations before subsequent blocks-- **Group `let`/`subject` together**, separate from `before`/`after` hooks with blank lines-- **Surround multi-line declarations with blank lines** — when a `let`, `let!`, `fab!`, or `subject` uses a `do...end` or multi-line `{ }` body, put a blank line above and below it, even when adjacent declarations are single-line. Single-line declarations can still pack together, but a multi-line block always breathes on both sides:-- ```rb- # bad — multi-line blocks stacked against neighbors- fab!(:author)- fab!(:topic) do- Fabricate(:topic, user: author, title: "Hello")- end- fab!(:reply) do- Fabricate(:post, topic: topic, user: author)- end- fab!(:tag)-- # good- fab!(:author)-- fab!(:topic) do- Fabricate(:topic, user: author, title: "Hello")- end-- fab!(:reply) do- Fabricate(:post, topic: topic, user: author)- end-- fab!(:tag)- ```-- **One blank line** before and after each `it`/`specify` block-- **Blank lines between logical chunks** within an example — separate setup, action, and assertion for readability--## Example Group Structure--- **Declaration order**: `subject` → `fab!`/`let!`/`let` → `before` → `after`-- **Use `context` blocks** to organize test conditions; avoid conditional logic in example descriptions-- **Pair context cases** — include both positive and negative contexts (e.g. "when present" and "when not present")-- **Use `fab!`** for shared test data, `let` for computed values or non-persisted objects-- **Prefer `let` over instance variables** — `let(:name) { "John" }` not `before { @name = "John" }`-- **Omit `:each`/`:example`** scope on `before`/`after`/`around` hooks (they're the default)-- **Use `:context` over `:all`** when specifying hook scope-- **Minimize `:context`-scoped hooks** to prevent state leakage--## Example Structure--- **One expectation per example** or use `aggregate_failures` tag for multiple expectations; apply consistently-- **Use `subject`** to eliminate repetition when multiple tests reference the same object-- **Name subjects explicitly** — `subject(:article) { ... }` not anonymous `subject { ... }` (unless using `is_expected`)-- **Use distinct subject names** across different contexts for clarity-- **Never stub methods on the subject** — adjust initialization or create a presenter instead-- **Use `specify`** for tests without descriptions; use `it` for described examples-- **Don't generate tests via iteration** — write each test explicitly-- **Avoid incidental state** — use matchers like `change` instead of depending on shared state-- **Balance DRY with clarity** — some duplication in tests is preferable to fragile shared setup-- **Load only needed data** — minimum objects required for the test-- **Freeze time with `freeze_time`** — don't stub `Time.now` or `Date.today`-- **Stub HTTP requests** with WebMock-- **Don't define classes in example groups** (they leak to global scope) — use `stub_const` or `Class.new`-- **Use explicit block expectations** — `expect { do_something }.to change(...)` not implicit block subjects--## Naming--- **Context descriptions**: start with "when", "with", or "without" — e.g. `context "when the user is logged in"`-- **Example descriptions**: prefer encoding the full scenario in the `it` description rather than deeply nesting `context` blocks; limit nesting to 2 levels max-- **Keep descriptions under 60 characters**-- **Avoid "should"** — use third-person present tense: `it "returns the summary"` not `it "should return the summary"`-- **Describe methods**: `.method_name` for class methods, `#method_name` for instance methods--## Expectations--- **Always use `expect` syntax** — never `should`--## Matchers--- **Use predicate matchers** — `expect(article).to be_published` not `expect(article.published?).to be true`-- **Use built-in matchers** — `expect(title).to include "lengthy"` not `expect(title.include?("lengthy")).to be true`-- **Avoid bare `be`** — use `be_truthy`, `be_nil`, `be_an(Type)` etc.-- **Extract custom matchers** for repeated expectation patterns-- **Avoid `any_instance_of`** — mock injected dependencies directly--## Capybara--- **Use negative selectors** — `have_no_selector` not `to_not have_selector`diff --git a/.skills/discourse-writing-rspec-tests/references/system-tests.md b/.skills/discourse-writing-rspec-tests/references/system-tests.mdindex 175ba591168..f8fc614063b 100644--- a/.skills/discourse-writing-rspec-tests/references/system-tests.md+++ b/.skills/discourse-writing-rspec-tests/references/system-tests.md@@ -18,6 +18,32 @@ expect(Post.count).to eq(1)Only reach into the database when no UI signal exists for the behavior being tested, which should be rare. If you find yourself needing database assertions, consider whether the feature is missing user-visible feedback.+## Test Transient States Deterministically++**Do not race transient UI states in system tests.** Loading spinners, in-flight error banners, optimistic updates, and skeleton placeholders may resolve before Capybara observes them, producing timing-dependent tests.++When the transient state is part of a browser-level user flow, hold it deterministically with the system-test infrastructure, such as `with_pending_requests` or `with_slow_upload`, and assert both the intermediate state and stable outcome. Use a QUnit component test instead when the behavior is local to a component and does not require browser-server integration.++## URL Assertions++**Use exact-string matches with `have_current_path`.** Do not pass a regular expression unless the URL genuinely contains a value you cannot predict, such as a UUID, generated token, or server-assigned ID.++```rb+# Good - catches extra parameters, wrong separators, and encoding bugs+expect(page).to have_current_path(+ "/admin/reports/site_traffic?end_date=2026-05-31&start_date=2026-05-01"+)++# Bad - tolerates extra parameters and wrong path prefixes+expect(page).to have_current_path(+ %r{\A/admin/reports/site_traffic\?.*start_date=2026-05-01}+)+```++When the framework produces a surprising query-parameter order, update the expected string instead of weakening the matcher. Ember sorts query parameters alphabetically during navigation, so the expected URL must use the order the user sees.++If an unpredictable value requires a regular expression, anchor it with `\A` and `\z` and match everything except that segment.+**Verify persistence by refreshing the page.** After a save action, refresh (or revisit) the current page and assert the saved state is still visible. This is what a real user would do to confirm their changes persisted.```rb@@ -169,6 +195,8 @@ Because the addon strips these in production, never use `data-test-*` for stylin**Always use page objects** - never write raw selectors or Capybara finders directly in test files. Encapsulate all selectors and interactions in page object classes. Only add methods that are actually used by your tests - don't add methods speculatively.+**Design page object APIs from the call site.** Page object methods should make the spec read in product and user language. Prefer explicit methods and named arguments that describe the behavior being exercised over generic helpers that require the spec to know implementation details. Domain objects and product-facing values are valid arguments, but route or query-parameter names, selector fragments, and serialized keys belong inside the page object so the spec remains stable when implementation details change.+**Prefer passing entire objects** to page object methods instead of just attributes. Let the page object extract what it needs:```rb