Skip to content

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

DEV: Improve writing-rspec-tests skill (#40057)

Alan Guo Xiang Tan5e577d063c70
diff --git a/.skills/writing-rspec-tests/SKILL.md b/.skills/writing-rspec-tests/SKILL.md
index 1e02488cdab..9c1b451b651 100644
--- a/.skills/writing-rspec-tests/SKILL.md
+++ b/.skills/writing-rspec-tests/SKILL.md
@@ -12,6 +12,7 @@ Discourse uses RSpec for testing. Follow these patterns for all test types.
- **Test behavior, not implementation** — test public interfaces; don't assert on internal state or private methods. Refactoring internals shouldn't break tests.
- **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.
- **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.
@@ -21,6 +22,7 @@ Discourse uses RSpec for testing. Follow these patterns for all test types.
- **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.
- **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.
- **Optimise for human readability** — minimise context overload when reading an example. Avoid too many indirections.
- **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.
@@ -72,5 +74,10 @@ bin/rspec spec/models/topic_spec.rb:15
## Specialized Test Types
+- **Request specs**: See [references/request-specs.md](references/request-specs.md) for controller/request spec structure, action-based `describe` grouping, and what to assert.
- **System tests**: See [references/system-tests.md](references/system-tests.md) for file naming, test structure, page objects, and scoping patterns.
- **Theme/component tests**: See [references/theme-tests.md](references/theme-tests.md) for theme upload helpers, settings, and directory structure.
+
+## Tracking Helpers
+
+See [references/tracking-helpers.md](references/tracking-helpers.md) for `DiscourseEvent.track_events`, `MessageBus.track_publish`, and `track_sql_queries` — block helpers that capture events, message-bus publishes, and SQL queries so tests can assert on side effects.
diff --git a/.skills/writing-rspec-tests/references/request-specs.md b/.skills/writing-rspec-tests/references/request-specs.md
new file mode 100644
index 00000000000..dc356e1ba10
--- /dev/null
+++ b/.skills/writing-rspec-tests/references/request-specs.md
@@ -0,0 +1,101 @@
+# Request Specs
+
+Discourse uses **request specs** (`spec/requests/`) rather than controller specs to test controllers. They drive real HTTP requests against the Rails router, so they verify routing, middleware, controller actions, and response payloads end-to-end.
+
+## File and Top-Level Naming
+
+- **File**: `spec/requests/<resource>_controller_spec.rb` — name after the controller it covers (e.g. `bookmarks_controller_spec.rb` for `BookmarksController`).
+- **Top-level**: `RSpec.describe SomeController do` — reference the controller class directly, not a string.
+
+```rb
+# frozen_string_literal: true
+
+RSpec.describe BookmarksController do
+ fab!(:user)
+
+ describe "#create" do
+ # ...
+ end
+end
+```
+
+## Group by Controller Action
+
+**One `describe` block per controller action**, named `"#action_name"`:
+
+```rb
+describe "#index" do
+end
+
+describe "#create" do
+end
+
+describe "#destroy" do
+end
+```
+
+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.
+
+Reserve bare descriptive strings (`describe "extensibility event"`) for cross-cutting concerns that don't map to a single action.
+
+## Scenarios Within an Action
+
+Use `context` blocks for scenarios within an action — pair positive and negative cases:
+
+```rb
+describe "#create" do
+ before { sign_in(user) }
+
+ it "creates the bookmark" do
+ post "/bookmarks.json", params: { bookmarkable_id: post.id, bookmarkable_type: "Post" }
+ expect(response.status).to eq(200)
+ end
+
+ context "when the user has reached the bookmark limit" do
+ before { SiteSetting.max_bookmarks_per_user = 1 }
+
+ it "returns a 400 with an explanatory error" do
+ # ...
+ end
+ end
+end
+```
+
+Keep nesting to 2 levels max (per the top-level testing principles). If a scenario needs more depth, flatten by encoding it into the `it` description.
+
+## Authentication
+
+Sign in inside the action's `describe` block (or a `context`), not at the top of the file — different actions often have different auth requirements:
+
+```rb
+describe "#create" do
+ before { sign_in(user) }
+ # ...
+end
+```
+
+For anonymous-user scenarios, omit `sign_in` and assert the expected redirect or 403.
+
+## What to Assert
+
+Request specs verify the **observable HTTP behavior** and any externally visible side effects:
+
+- **Response status**: `expect(response.status).to eq(200)`
+- **Response body**: `expect(response.parsed_body["errors"]).to include(...)` — use `parsed_body` for JSON
+- **Persisted state**: `expect(Bookmark.find_by(id: bookmark.id)).to eq(nil)` — direct DB checks are fine here, since the controller's job is to mutate state
+- **Emitted events / enqueued jobs** when relevant
+
+**Don't** assert on internal method calls (`Controller.any_instance.expects(:foo)`) — that couples the test to implementation. If the response and state are correct, the implementation is correct.
+
+## Issuing Requests
+
+Make real HTTP calls — don't stub the controller:
+
+```rb
+get "/bookmarks.json"
+post "/bookmarks.json", params: { ... }
+put "/bookmarks/#{id}.json", params: { ... }
+delete "/bookmarks/#{id}.json"
+```
+
+Use the `.json` suffix for JSON endpoints; omit it for HTML endpoints.
diff --git a/.skills/writing-rspec-tests/references/rspec-style-guide.md b/.skills/writing-rspec-tests/references/rspec-style-guide.md
index d234838a36e..af8e6609009 100644
--- a/.skills/writing-rspec-tests/references/rspec-style-guide.md
+++ b/.skills/writing-rspec-tests/references/rspec-style-guide.md
@@ -8,6 +8,32 @@
- **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
diff --git a/.skills/writing-rspec-tests/references/system-tests.md b/.skills/writing-rspec-tests/references/system-tests.md
index 57f90cebc1f..f1b9525eef1 100644
--- a/.skills/writing-rspec-tests/references/system-tests.md
+++ b/.skills/writing-rspec-tests/references/system-tests.md
@@ -69,8 +69,6 @@ RSpec.describe "Filter sidebar" do
end
```
-The `type: :system` metadata is inferred automatically from the file's location under `spec/system/`, so no explicit `system: true` is needed on the describe block.
-
**Key patterns:**
- Instantiate page objects with `let`
- Use `context` blocks to group related scenarios
@@ -169,6 +167,49 @@ expect(sidebar).to have_category_name(category)
expect(sidebar).to have_category_link(category)
```
+## Composing Page Objects
+
+**Don't stuff everything into a single page object.** Identify UI boundaries (header, sidebar, composer, post, modal, etc.) and split them into separate component page objects. The main page object exposes methods that return instances of those components.
+
+```rb
+# Good - main page composes scoped components
+module PageObjects
+ module Pages
+ class Topic < PageObjects::Pages::Base
+ def header
+ PageObjects::Components::TopicHeader.new
+ end
+
+ def composer
+ PageObjects::Components::Composer.new
+ end
+
+ def post_by_number(number)
+ PageObjects::Components::Post.new(".topic-post[data-post-number='#{number}']")
+ end
+ end
+ end
+end
+
+# In test
+topic_page.visit_topic(topic)
+topic_page.header.click_reply
+topic_page.composer.fill_in_body("Hello")
+expect(topic_page.post_by_number(2)).to be_liked
+```
+
+```rb
+# Avoid - one mega page object with every selector and interaction
+class Topic < PageObjects::Pages::Base
+ def click_header_reply; end
+ def fill_composer_body(text); end
+ def post_2_liked?; end
+ # ...dozens more methods spanning unrelated UI regions
+end
+```
+
+Component page objects keep selectors local to the region they describe, make tests read like the UI is structured, and let components be reused across pages (e.g. the composer appears in multiple pages).
+
## Scoping Components to Elements
When a component appears multiple times on a page (e.g., a like button on each post), **always scope components to their parent element.**
diff --git a/.skills/writing-rspec-tests/references/tracking-helpers.md b/.skills/writing-rspec-tests/references/tracking-helpers.md
new file mode 100644
index 00000000000..eeea4b43d5b
--- /dev/null
+++ b/.skills/writing-rspec-tests/references/tracking-helpers.md
@@ -0,0 +1,65 @@
+# Tracking Helpers
+
+Discourse provides a few block helpers for asserting on side effects produced inside a unit of work. They capture what happened during the block and return the collected data so the test can assert on it.
+
+## `DiscourseEvent.track_events`
+
+Captures `DiscourseEvent.trigger` calls made inside the block. Returns an array of `{ event_name:, params: }` hashes.
+
+```rb
+events = DiscourseEvent.track_events { PostDestroyer.new(user, post).destroy }
+
+expect(events.map { |e| e[:event_name] }).to include(:post_destroyed)
+```
+
+Filter by event name (and optionally by exact args) by passing them in:
+
+```rb
+events =
+ DiscourseEvent.track_events(:user_first_visit_to_topic) do
+ TopicUser.track_visit!(topic.id, user.id)
+ end
+
+expect(events).to be_blank
+```
+
+Use `DiscourseEvent.track(event_name, args:) { ... }` (singular) when you only care about the first matching event — it returns the event hash directly instead of an array.
+
+## `MessageBus.track_publish`
+
+Captures `MessageBus.publish` calls made inside the block. Returns an array of `MessageBus::Message` objects, each exposing `channel`, `data`, `user_ids`, `group_ids`, and `client_ids`.
+
+```rb
+messages = MessageBus.track_publish { described_class.publish_new(private_message) }
+
+expect(messages.map(&:channel)).to contain_exactly(described_class.user_channel(user_2.id))
+
+data = messages.first.data
+expect(data["message_type"]).to eq(described_class::NEW_MESSAGE_TYPE)
+```
+
+Pass a channel name to capture only publishes to that channel:
+
+```rb
+messages = MessageBus.track_publish(channel) { TopicUser.update_last_read(user, topic.id, 2, 1, 0) }
+```
+
+## `track_sql_queries`
+
+Captures the SQL executed by ActiveRecord and MiniSQL inside the block. Returns an array of SQL strings (with `CACHE` and `SCHEMA` queries filtered out). Useful for N+1 regression checks.
+
+```rb
+queries_for_one =
+ track_sql_queries do
+ components.each { |c| ComponentIndexSerializer.new(c, root: false).as_json }
+ end
+
+queries_for_two =
+ track_sql_queries do
+ larger_components.each { |c| ComponentIndexSerializer.new(c, root: false).as_json }
+ end
+
+expect(queries_for_two.size).to eq(queries_for_one.size)
+```
+
+Compare query *counts* across scaled-up inputs to assert "constant queries regardless of N". Asserting on the exact SQL strings is fragile — prefer counts or shape checks.