Skip to content

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

DEV: Add writing-rspec-tests agent skill (#37941)

Alan Guo Xiang Tanb8249488d685
diff --git a/.skills/writing-rspec-tests/SKILL.md b/.skills/writing-rspec-tests/SKILL.md
new file mode 100644
index 00000000000..1e02488cdab
--- /dev/null
+++ b/.skills/writing-rspec-tests/SKILL.md
@@ -0,0 +1,76 @@
+---
+name: writing-rspec-tests
+description: Write and structure RSpec tests for Discourse core, plugins, themes, or theme components. Use when creating or modifying model specs, controller specs, service specs, job specs, system tests, or integration tests. Covers fabricators, page objects, test structure, and theme test setup.
+---
+
+# Writing RSpec Tests
+
+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.
+- **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.
+- **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.
+- **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.
+- **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.
+
+## 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 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.
+
+## Test Efficiency
+
+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
+
+## Running Tests
+
+```sh
+# Run specific file
+bin/rspec spec/models/topic_spec.rb
+
+# Run specific line
+bin/rspec spec/models/topic_spec.rb:15
+```
+
+## Specialized Test Types
+
+- **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.
diff --git a/.skills/writing-rspec-tests/references/rspec-style-guide.md b/.skills/writing-rspec-tests/references/rspec-style-guide.md
new file mode 100644
index 00000000000..d234838a36e
--- /dev/null
+++ b/.skills/writing-rspec-tests/references/rspec-style-guide.md
@@ -0,0 +1,64 @@
+# 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
+- **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/writing-rspec-tests/references/system-tests.md b/.skills/writing-rspec-tests/references/system-tests.md
new file mode 100644
index 00000000000..57f90cebc1f
--- /dev/null
+++ b/.skills/writing-rspec-tests/references/system-tests.md
@@ -0,0 +1,255 @@
+# System Tests
+
+Discourse uses Rails system tests with RSpec and Capybara. Tests run both server and client code together.
+
+## Assert What Users See, Not Database State
+
+System tests simulate real user interactions. **Assert on visible UI state, not database records.** If a user can't see it on the page, don't check it in the database.
+
+```rb
+# Good - asserts what the user sees
+expect(topic_page).to have_post(text: "Hello world")
+expect(toasts).to have_success("Topic created")
+
+# Bad - checks database state the user can't see
+expect(Topic.last.title).to eq("Hello world")
+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.
+
+**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
+# Good - refreshes and verifies saved state
+admin_settings_page.save
+expect(toasts).to have_success("Settings saved")
+
+page.refresh
+
+expect(admin_settings_page).to have_setting_value("site_name", "My Forum")
+
+# Bad - only checks before refresh, or checks the database
+admin_settings_page.save
+expect(SiteSetting.site_name).to eq("My Forum")
+```
+
+## File Naming
+
+Use `action_scenario_spec.rb` pattern - describe what the test does:
+- `filter_sidebar_spec.rb` → `RSpec.describe "Filter sidebar"`
+- `toggle_dark_mode_spec.rb` → `RSpec.describe "Toggle dark mode"`
+- `create_topic_with_template_spec.rb` → `RSpec.describe "Create topic with template"`
+
+Avoid generic names like `feature_spec.rb` or `my_feature_spec.rb`.
+
+## Test Structure
+
+```rb
+# frozen_string_literal: true
+
+RSpec.describe "Filter sidebar" do
+ fab!(:user)
+ fab!(:category)
+
+ let(:sidebar) { PageObjects::Components::Sidebar.new }
+
+ context "when logged in" do
+ before { sign_in(user) }
+
+ it "filters and displays categories" do
+ visit("/")
+
+ sidebar.filter(category.name)
+
+ expect(sidebar).to have_category(category)
+ expect(sidebar).to have_no_category("Unrelated")
+ end
+ end
+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
+- Batch related assertions in a single `it` block
+- Never use raw selectors in test files - delegate to page objects
+
+## Writing `it` Block Descriptions
+
+Describe the **user interaction and expected experience**, not implementation details. System tests verify what users see and do, so descriptions should read like user stories.
+
+```rb
+# Good - describes user experience
+it "allows a user to filter categories in the sidebar"
+it "displays an error when submitting an empty title"
+it "navigates to the topic after clicking a search result"
+
+# Bad - describes implementation details
+it "preserves the tag filter in the URL when switching categories"
+it "updates the model count after deletion"
+it "sets the correct query param on filter change"
+```
+
+## Freezing Time
+
+For time-sensitive system tests, use the `time:` metadata key instead of calling `freeze_time` manually. This freezes **both** the Ruby server time and the Playwright browser clock simultaneously:
+
+```rb
+it "shows the post timestamp correctly", time: Time.zone.parse("2024-01-15 10:00:00") do
+ visit(topic_path(topic))
+ expect(post_component).to have_timestamp("Jan 15")
+end
+```
+
+**Why this matters:** In system tests, JavaScript also needs to see the frozen time (e.g. for relative timestamps like "5 minutes ago"). The `time:` metadata calls both `freeze_time` and `pw_page.clock.set_fixed_time` under the hood. Using plain `freeze_time` only freezes the Ruby side, leaving the browser clock running normally.
+
+## Common Helpers
+
+| Helper | Purpose |
+|--------|---------|
+| `sign_in(user)` | Sign in as a user |
+| `visit(path)` | Navigate to a page |
+| `puts` | Debug server-side code (Ruby) |
+| `console.log` | Debug client-side code (JavaScript) |
+| `pause_test` | Pause to view visual state (use with `SELENIUM_HEADLESS=0`) |
+
+## Page Objects
+
+**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.
+
+**Prefer passing entire objects** to page object methods instead of just attributes. Let the page object extract what it needs:
+
+```rb
+# Good - page object receives the full object
+def has_tag?(tag)
+ has_css?("#{SELECTOR} .discourse-tag", text: tag.name)
+end
+
+# In test
+expect(component).to have_tag(tag)
+```
+
+```rb
+# Avoid - caller extracts the attribute
+def has_tag?(name)
+ has_css?("#{SELECTOR} .discourse-tag", text: name)
+end
+
+# In test
+expect(component).to have_tag(tag.name)
+```
+
+**Combine related assertions** into single page object methods when checking multiple aspects of the same element:
+
+```rb
+# Good - checks both content and link in one assertion
+def has_category_link?(category)
+ has_css?("a.category-link[href='/c/#{category.slug}']", text: category.name)
+end
+
+# In test - single assertion covers both aspects
+expect(sidebar).to have_category_link(category)
+```
+
+```rb
+# Avoid - separate methods when they could be combined
+def has_category_name?(category)
+ has_css?(".category-name", text: category.name)
+end
+
+def has_category_link?(category)
+ has_css?("a[href='/c/#{category.slug}']")
+end
+
+# In test - multiple assertions for one element
+expect(sidebar).to have_category_name(category)
+expect(sidebar).to have_category_link(category)
+```
+
+## 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.**
+
+**Bad - ambiguous component:**
+```rb
+let(:like_button) { PageObjects::Components::LikeButton.new }
+
+it "likes a reply" do
+ topic_page.visit_topic(topic)
+ like_button.click # Which post's like button?
+ expect(like_button).to be_liked # Ambiguous
+end
+```
+
+**Good - component scoped through parent:**
+```rb
+let(:topic_page) { PageObjects::Pages::Topic.new }
+
+it "likes a reply" do
+ topic_page.visit_topic(topic)
+ topic_page.post_by_number(2).click_like
+ expect(topic_page.post_by_number(2)).to be_liked
+end
+```
+
+**Two valid patterns for scoping:**
+
+1. **Access through parent page object** (preferred) - The parent provides a method that returns a scoped component:
+ ```rb
+ # In page object
+ def post_by_number(number)
+ PageObjects::Components::Post.new(".topic-post[data-post-number='#{number}']")
+ end
+
+ # In test
+ topic_page.post_by_number(2).click_like
+ ```
+
+2. **Pass scoping element to constructor** - Instantiate with a selector that scopes to the specific instance:
+ ```rb
+ let(:second_post) { PageObjects::Components::Post.new(".topic-post[data-post-number='2']") }
+
+ it "likes the second post" do
+ second_post.click_like
+ expect(second_post).to be_liked
+ end
+ ```
+
+The first pattern is preferred because it keeps selectors out of test files and makes the relationship explicit.
+
+## S3 Upload System Tests
+
+System specs involving S3 uploads use MinIO (a local S3-compatible server). The test infrastructure automatically downloads and runs MinIO with an isolated data store during specs.
+
+**Writing S3 system specs:** Call `setup_or_skip_s3_system_test` as the very first line in each `it` block. This configures the S3 environment and skips the test if S3 specs aren't enabled:
+
+```rb
+it "uploads a file to S3" do
+ setup_or_skip_s3_system_test
+
+ # your test code here
+end
+```
+
+**Running S3 system specs:** S3-related specs are skipped by default. Enable them with the `RUN_S3_SYSTEM_SPECS` environment variable:
+
+```sh
+RUN_S3_SYSTEM_SPECS=1 bin/rspec spec/system/s3_uploads_spec.rb
+```
+
+**Local setup required:** MinIO must be reachable at specific hostnames. Add entries to `/etc/hosts`:
+
+```sh
+# Linux
+echo "127.0.0.1 minio.local discoursetest.minio.local" | sudo tee -a /etc/hosts
+
+# macOS — also needs IPv6 entries
+echo "127.0.0.1 minio.local discoursetest.minio.local" | sudo tee -a /etc/hosts
+echo "::1 minio.local discoursetest.minio.local" | sudo tee -a /etc/hosts
+echo "fe80::1%lo0 minio.local discoursetest.minio.local" | sudo tee -a /etc/hosts
+```
+
+To use a custom MinIO hostname, set `MINIO_RUNNER_MINIO_DOMAIN`.
diff --git a/.skills/writing-rspec-tests/references/theme-tests.md b/.skills/writing-rspec-tests/references/theme-tests.md
new file mode 100644
index 00000000000..321126b25c2
--- /dev/null
+++ b/.skills/writing-rspec-tests/references/theme-tests.md
@@ -0,0 +1,84 @@
+# Theme System Tests
+
+Additional guidance for testing themes and theme components.
+
+## Directory Structure
+
+```
+theme/
+ spec/
+ system/
+ filter_sidebar_spec.rb
+ toggle_dark_mode_spec.rb
+ page_objects/
+ components/
+ sidebar.rb
+```
+
+- Tests go in `spec/system`
+- Files must match `*_spec.rb` pattern
+
+## Test Structure
+
+```rb
+# frozen_string_literal: true
+
+require_relative "page_objects/components/sidebar"
+
+RSpec.describe "Filter sidebar" do
+ let!(:theme) { upload_theme }
+ # For components: let!(:theme) { upload_theme_component }
+
+ fab!(:category)
+
+ let(:sidebar) { PageObjects::Components::Sidebar.new }
+
+ it "filters and displays categories" do
+ visit("/")
+
+ sidebar.filter(category.name)
+
+ expect(sidebar).to have_category(category)
+ end
+end
+```
+
+## Helpers
+
+| Helper | Purpose |
+|--------|---------|
+| `upload_theme` | Upload the theme being tested |
+| `upload_theme_component` | Upload a theme component |
+
+## Theme Settings
+
+```rb
+it "respects settings" do
+ theme.update_setting(:my_setting, false)
+ theme.save!
+
+ visit("/")
+ expect(page).not_to have_css(".my-feature")
+end
+```
+
+## Running Theme Tests
+
+Clone themes into `tmp/themes` in the Discourse directory, then run from Discourse root:
+
+```sh
+# Run all theme system tests
+bin/rspec tmp/themes/my-theme/spec/system
+
+# Run specific file
+bin/rspec tmp/themes/my-theme/spec/system/my_spec.rb
+
+# Run specific line
+bin/rspec tmp/themes/my-theme/spec/system/my_spec.rb:15
+
+# Run with visible browser
+SELENIUM_HEADLESS=0 bin/rspec tmp/themes/my-theme/spec/system
+
+# If theme relies on a plugin being enabled
+LOAD_PLUGINS=1 bin/rspec tmp/themes/my-theme/spec/system
+```