# Ruby on Rails Recipes

URL: https://developertoolkit.ai/en/cookbook/backend-recipes/ruby-rails-patterns/
Description: Agent recipes for Rails 8.1 — generators over hand-written files, RSpec loops, bin/ci as the definition of done, safe migrations and N+1 checks that fail specs.

Ruby on Rails recipes for AI coding agents are prompts and project settings that make Claude Code, Codex and Cursor ship trustworthy Rails 8.1 changes: generators instead of hand-written boilerplate, RSpec request specs written before the code, `bin/ci` as the definition of done, migrations checked for reversibility and lock safety, and N+1 queries that fail a spec.

This page is for Rails developers who already let an agent write most of a feature, and for tech leads who want the same gates enforced in CI for the whole team. The situation it fixes: the agent's pull request is green, but it hand-wrote a migration with a timestamp from last year, edited `db/schema.rb` directly, rendered a list with `order.customer.name` in the loop, and "fixed" a failing spec by changing the expected value. The recipes below make the agent run into Rails' conventions, generators and CI runner on every turn, so you review evidence instead of diffs.

## What these Rails recipes give you

- A `config/ci.rb` that turns `bin/ci` into the gate the agent must pass: RuboCop, Brakeman, RSpec and a migration-reversibility step.
- An `AGENTS.md` for a Rails app, wired into Claude Code, Codex and Cursor.
- A generator-first prompt that stops the agent from hand-writing migrations, models and specs.
- A spec-first loop for a Rails endpoint, from acceptance criteria to failing request specs to the implementation.
- A Claude Code `Stop` hook that refuses "done" until RuboCop and RSpec pass, and a CI job that is the mechanical gate for Codex and Cursor.
- N+1 detection that fails specs, with the choice between Bullet, Prosopite and `strict_loading` tested on Rails 8.1.4.
- A migration recipe with `strong_migrations`, a schema-drift check and a human sign-off on destructive changes.
- Mutation testing with `mutant` to show whether the agent's specs would catch a bug.

## Which Ruby, Rails and gem versions do these recipes assume?

Agents mix APIs from Rails 5, 6, 7 and 8 because their training data does. Tell the agent the versions and pin them (`.ruby-version`, `Gemfile.lock`) so it cannot drift. These were current on 2026-09-26:

| Component | Version | Source (checked 2026-09-26) |
| --- | --- | --- |
| Ruby | 4.0.7 (2026-09-15) | ruby-lang.org releases |
| Rails | 8.1.4 (2026-09-24); requires Ruby 3.2 or later | rubygems.org |
| `rspec-rails` / `factory_bot_rails` | 8.0.4 / 6.5.1 | rubygems.org |
| `rubocop` / `rubocop-rails` / `rubocop-rails-omakase` | 1.91.0 / 2.38.0 / 1.1.0 | rubygems.org |
| `brakeman` | 8.0.6 | rubygems.org |
| `bullet` / `prosopite` | 8.2.0 / 2.2.0 | rubygems.org |
| `strong_migrations` | 2.8.0 | rubygems.org |
| `mutant` / `mutant-rspec` | 0.17.0 | rubygems.org |
| `ruby-lsp` | 0.26.11 | rubygems.org |

The Rails, RSpec, Bullet, Prosopite, `strict_loading` and `mutant` results come from a fresh Rails 8.1.4 app (Ruby 3.3.6, SQLite, `rspec-rails` 8.0.4) on 2026-09-26. Rails 8.1.4 requires Ruby 3.2.0 or later, so it installs on Ruby 4.0, but the recipes were not rerun on 4.0.7. The PostgreSQL workflow and the `strong_migrations` steps follow the gems' documentation.

Stay on your tool's default model and raise effort before switching models. Current defaults and prices are on the [AI models hub](/en/ecosystem/models/).

## How do you make a Rails app agent-ready?

Put the gates in files the agent cannot forget. Rails 8.1 already generates most of them: `rails new` writes `.rubocop.yml` (inheriting `rubocop-rails-omakase`), `bin/brakeman`, `bin/bundler-audit` and a local CI runner, `bin/ci`, that reads its steps from `config/ci.rb` and exits non-zero when any step fails. Add the two steps an agent most often skips:

```ruby title="config/ci.rb"
# Run using bin/ci
CI.run do
  step "Setup", "bin/setup --skip-server"
  step "Style: Ruby", "bin/rubocop"
  step "Security: Gem audit", "bin/bundler-audit"
  step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error"
  step "Tests: RSpec", "bin/rspec"
  step "Migrations: reversible", "bin/rails db:migrate:redo STEP=1"
end
```

The last step rolls back the newest migration and applies it again. On a test app, an agent-written `remove_column :orders, :total_cents` without a type raised `ActiveRecord::IrreversibleMigration` in that step and `bin/ci` exited with status 1. Create the `bin/rspec` binstub with `bundle binstubs rspec-core`.

Rails defaults to Minitest. If you use RSpec, add `rspec-rails` to the `:development, :test` group, run `bin/rails generate rspec:install`, and tell the generators which specs you want, so `bin/rails generate` stops producing view and helper specs nobody maintains:

```ruby title="config/application.rb"
config.generators do |g|
  g.test_framework :rspec, view_specs: false, helper_specs: false, routing_specs: false
  g.helper false
end
```

With this block, `bin/rails generate scaffold Invoice number:string order:references` creates only a model spec and a request spec. Uncomment `config.example_status_persistence_file_path = "spec/examples.txt"` in `spec/spec_helper.rb` (the generated file ships it inside a `=begin` block). Without it, `bin/rspec --only-failures` has nothing to read, and the agent re-runs the whole suite on every iteration.

## What goes in AGENTS.md for a Rails app?

Write the commands the agent must run, in the order it must run them, and the few rules a generic Rails model gets wrong in your codebase. Leave out anything RuboCop or `config/ci.rb` already enforces.

```markdown title="AGENTS.md"
# Shop (Rails 8.1, Ruby 4.0, PostgreSQL, RSpec, Hotwire)

## Commands (run from the repo root)
- One spec file or example: `bin/rspec spec/requests/orders_spec.rb:12`
- Failures from the last run: `bin/rspec --only-failures`
- Lint with safe autocorrect: `bin/rubocop -a`
- Full gate: `bin/ci` (RuboCop, Brakeman, bundler-audit, RSpec, migration redo)
- Preview a generator: add `--pretend` to any `bin/rails generate` command

## Definition of done
`bin/ci` passes. Report the command you ran and its last lines.

## Rules
- Create models, migrations, controllers, jobs and mailers with `bin/rails generate`, never by hand.
- Never edit db/schema.rb or an existing migration. Add a new migration and run `bin/rails db:migrate`.
- Specs are the specification. If a spec fails, fix app/, not spec/. Ask before changing an expectation.
- Request specs, not controller specs. Use FactoryBot factories from spec/factories.
- Any action that renders a collection uses `includes` or `preload`; the N+1 detector fails the spec otherwise.
- Never add `# rubocop:disable`, a Brakeman ignore entry or `safety_assured` without asking.
- Money is integer cents (`*_cents`), never Float.
```

Each tool loads the same file differently:

**Claude Code**

    Create a `CLAUDE.md` whose first line imports the shared file, then add any Claude-only lines below it:

    ```markdown title="CLAUDE.md"
    @AGENTS.md
    ```

    Claude Code 2.1.277 and later also read `AGENTS.md` directly when a project has no `CLAUDE.md` (first-party sessions; v2.1.281 on Bedrock, Google Cloud, Foundry and LLM gateways; both release channels on 2026-10-12). The import works on every version and channel.

**Codex**

    Codex reads `AGENTS.md` before it starts work. Run `/init` in the TUI to draft one, then replace the draft with the file above. Since codex-cli 0.150.0, a project Codex does not trust does not supply its `AGENTS.md`, so trust the repository when Codex asks.

**Cursor**

    Add an always-applied project rule (the format is on [Cursor project rules](/en/cursor-ide/quick-start/project-rules/)) that repeats the Commands and Rules sections of the file above. Commit the rule with the repository.

**Copy-paste prompt: draft AGENTS.md from an existing Rails app**

```text
Read Gemfile, Gemfile.lock, .ruby-version, config/application.rb, config/ci.rb (if present), .rubocop.yml, spec/rails_helper.rb and spec/spec_helper.rb, and list the directories under app/ and spec/. Write AGENTS.md with: (1) a one-line description naming the Rails and Ruby versions, the database and the test framework; (2) the exact commands for one spec example, failed specs only, lint with safe autocorrect, the full gate and a generator dry run, as they work in THIS repo; (3) a "Definition of done" line; (4) at most eight rules, each one a convention you can see this codebase follows and a generic Rails model would get wrong. Do not restate anything RuboCop already enforces. Run every command you list and tell me which ones failed.
```

[Shared agent rules](/en/cto-scorecard-guide/shared-agent-rules/) explains how to keep one source of truth when a team uses all three tools.

## How do you make the agent use Rails generators instead of writing files by hand?

A hand-written migration can break Rails in ways specs do not show: a timestamp that sorts before migrations already in production, a `Migration[7.0]` superclass copied from training data, or a model without its spec. Generators produce the file names, the migration version and the spec skeletons your configuration asks for. The `--pretend` flag shows what a generator would create without writing anything, which makes it a cheap plan step:

```bash
# terminal: show the plan, write nothing
bin/rails generate model Refund order:references amount_cents:integer reason:string --pretend
```

**Copy-paste prompt: generator-first feature scaffolding**

```text
We need a Refund model: belongs to Order, amount_cents integer (not null, > 0), reason string (not null), status string with the values requested, approved and rejected, default requested. First run the bin/rails generate command you intend to use with --pretend and show me its output. Do not write any file by hand that a generator can create. After I approve, run the generator without --pretend, then edit the generated migration to add null: false, the default and a check constraint for amount_cents > 0, and add the model validations and the enum. Run bin/rails db:migrate and bin/rspec spec/models/refund_spec.rb, and show me the diff of db/schema.rb that the migration produced.
```

The last line matters: the `db/schema.rb` diff is the shortest honest summary of what a migration does. Read that, not the Ruby.

## How do you run a spec-first loop for a Rails endpoint?

Specify the behaviour, have the agent write failing request specs, check that they fail for the right reason, and only then let it write the implementation. Request specs go through routing, middleware and the database, so they are the oracle closest to what a user sees.

1. **Write the acceptance criteria.** Three to six observable behaviours, each one a sentence a spec can check. [Acceptance criteria an agent can verify](/en/workflows/plan/acceptance-criteria/) shows the format.

2. **Ask for failing specs only.** Use the first prompt below. Stop the agent once the specs load and fail.

3. **Read the failures, not the code.** Each spec should fail on its expectation (`expected 201, got 404`), not on a missing factory or a load error. A spec that fails for the wrong reason will pass for the wrong reason too.

4. **Ask for the implementation.** Use the second prompt. The loop ends when `bin/ci` passes, not when the agent says it is done.

5. **Check spec strength.** Run `mutant` on the changed methods (see [How do you know the agent's specs would catch a bug?](#how-do-you-know-the-agents-specs-would-catch-a-bug)).

**Copy-paste prompt: failing request specs for a refund endpoint**

```text
We are adding POST /orders/:order_id/refunds (JSON). Acceptance criteria:
1. A valid refund returns 201 with the refund id and status "requested".
2. amount_cents greater than the order's remaining refundable amount returns 422 with an error on amount_cents, and no row is created.
3. A missing or blank reason returns 422 with an error on reason.
4. A refund for another customer's order returns 404, not 403.
5. Listing GET /orders/:order_id/refunds for an order with 5 refunds runs a constant number of queries (the N+1 detector must stay silent).

Write ONLY specs, in spec/requests/refunds_spec.rb, with FactoryBot factories in spec/factories (create any that are missing). Do not create or change anything under app/, config/ or db/. Then run bin/rspec spec/requests/refunds_spec.rb and show me each failure message. Stop there.
```

**Copy-paste prompt: implement until bin/ci is green**

```text
Implement the refunds endpoints so every example in spec/requests/refunds_spec.rb passes. Use bin/rails generate for any new controller or migration. Scope the order lookup through the current customer so criterion 4 holds. Do not modify any file under spec/. Iterate with bin/rspec --only-failures. When you think you are done, run bin/ci and paste its last 20 lines. If a spec still fails, tell me which acceptance criterion the code violates instead of changing the spec.
```

[Protect the oracle](/en/workflows/test/protect-the-oracle/) explains why the "do not modify spec/" instruction needs a mechanical backstop as well, which the next section adds.

## How do you stop the agent from declaring done before the specs pass?

An instruction in `AGENTS.md` is advice. A hook or a CI check is a gate. Claude Code gets a local gate from the `Stop` hook below. Codex and Cursor have hooks too, but the setups below use a prompt and a project rule, so for them the CI job after the tabs remains the gate.

**Claude Code**

    A `Stop` hook runs when Claude finishes responding. Exit code 2 prevents the stop and shows the hook's stderr to Claude, which then keeps working. Run the fast part of the gate here and leave the full `bin/ci` (which also audits gems over the network) to the end of the task and to CI:

    ```bash title=".claude/hooks/rails-gate.sh"
    #!/usr/bin/env bash
    # Refuse "done" until RuboCop and RSpec pass.
    input=$(cat)
    # Already continuing because of a stop hook: stop and report instead of looping.
    [ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0
    cd "$CLAUDE_PROJECT_DIR" || exit 0
    # No changes to code, specs or schema since the branch left main: nothing to check.
    base=$(git merge-base HEAD origin/main 2>/dev/null || echo HEAD)
    [ -z "$(git status --porcelain -- app spec db config lib)" ] &&
      git diff --quiet "$base" -- app spec db config lib && exit 0
    if ! out=$(bin/rubocop 2>&1); then
      echo "RuboCop failed. Fix the code; run bin/rubocop -a for safe fixes; never add rubocop:disable:" >&2
      echo "$out" | grep -E "^[^ ].+:[0-9]+:[0-9]+: " | head -30 >&2
      exit 2
    fi
    if ! out=$(bin/rspec 2>&1); then
      echo "RSpec failed. Fix app/, never spec/. Re-run with bin/rspec --only-failures:" >&2
      echo "$out" | tail -40 >&2
      exit 2
    fi
    exit 0
    ```

    The script needs `jq`. Because it exits 0 when `stop_hook_active` is `true`, a failing gate forces one retry, and then Claude stops and reports instead of looping on a spec that cannot pass. The guard skips the run when nothing under `app`, `spec`, `db`, `config` or `lib` differs from `origin/main`, whether the change is uncommitted or already committed; change `origin/main` if your default branch has another name. [Hooks automation](/en/claude-code/automate/hooks-automation/) explains how to allow more than one retry and covers the other events.

    Register it in the project settings and make the script executable (`chmod +x`):

    ```json title=".claude/settings.json"
    {
      "hooks": {
        "Stop": [
          {
            "hooks": [
              { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/rails-gate.sh", "timeout": 600 }
            ]
          }
        ]
      }
    }
    ```

    On a large suite, replace `bin/rspec` with the spec files that match the changed files, and keep the full run in CI.

**Codex**

    `bundle install` needs the network, and the `workspace-write` sandbox has no network access unless you enable it. Install gems first, outside the agent, then run the loop without network:

    ```bash
    bundle install
    codex exec --sandbox workspace-write "Implement the refunds endpoints so every example in spec/requests/refunds_spec.rb passes. Do not modify spec/. Finish only when 'bin/rubocop' and 'bin/rspec' both pass; print the last lines of each."
    ```

    An SQLite test database is a file in the workspace, so it works inside the sandbox. If your specs need a PostgreSQL server and the sandbox blocks the connection, run the database specs in CI and give the local loop the model specs only. If the task is adding a gem, enable network for that run only with `-c sandbox_workspace_write.network_access=true`.

    The prompt is still an instruction: nothing stops the run from ending with red specs. For a local gate, run the same RuboCop and RSpec checks from a Codex `Stop` hook (`hooks` is a stable feature in 0.157.1; check it with `/hooks`, and note that hooks need persisted trust). Otherwise the CI job below is the mechanical gate for Codex.

**Cursor**

    Paste the implementation prompt into the agent, in Plan Mode first if the change touches models, controllers and migrations together. Put the Definition of done in the project rule so the agent runs `bin/ci` before it reports back. The mechanical gate for Cursor runs after the pull request opens: the CI job below, plus Bugbot if your team uses it for review.

Whatever runs locally, CI is the gate that decides. Run the same checks there with a read-only token and a throwaway PostgreSQL service:

```yaml title=".github/workflows/rails-gates.yml"
name: rails-gates
on:
  pull_request:
    types: [opened, synchronize, reopened, labeled, unlabeled]
permissions:
  contents: read
jobs:
  gates:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_HOST_AUTH_METHOD: trust  # disposable CI database, no credential
        ports: ["5432:5432"]
        options: --health-cmd="pg_isready" --health-interval=10s --health-timeout=5s --health-retries=3
    env:
      RAILS_ENV: test
      DATABASE_URL: postgres://postgres@localhost:5432/shop_test
    steps:
      - uses: actions/checkout@v7
        with:
          persist-credentials: false
          fetch-depth: 2   # the PR merge commit and its base parent
      - name: Existing specs unchanged
        if: ${{ !contains(github.event.pull_request.labels.*.name, 'spec-change-approved') }}
        run: |
          changed=$(git diff --name-only --diff-filter=MDR HEAD^1 HEAD -- spec/)
          if [ -n "$changed" ]; then
            echo "Existing specs modified, moved or deleted; a reviewer must add the spec-change-approved label:"
            echo "$changed"
            exit 1
          fi
      - uses: ruby/setup-ruby@v1
        with:
          bundler-cache: true
      - run: bin/rubocop
      - run: bin/bundler-audit
      - run: bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error
      - run: bin/rails db:create db:migrate
      - run: git diff --exit-code db/schema.rb   # migrations and schema.rb agree
      - run: bin/rails db:migrate:redo STEP=1     # newest migration is reversible
      - run: bin/rspec
```

The "Existing specs unchanged" step fails when the pull request modifies, renames or deletes an existing file under `spec/`, so the agent cannot quietly move an expected value or drop a failing spec; new spec files pass. After reviewing the spec change, a person adds the `spec-change-approved` label, which starts a new run that skips the step (re-running the old job does not work, because it reuses the original event and does not see the label). The step is only a gate if the pull request cannot remove it: GitHub runs the workflow file from the pull request itself, so put `/.github/` under `CODEOWNERS` and require that review in branch protection or a ruleset. The `git diff` step fails when the agent edited `db/schema.rb` by hand or committed a migration without the schema it produces.

## How do you catch N+1 queries in agent-written Rails code?

Agents readily write the N+1 loop, because `@orders.each { |o| o.customer.name }` is correct Ruby and every spec with one record passes. The fix is a detector that turns the pattern into a failing spec. Each row below was tested on Rails 8.1.4 on 2026-09-26:

| Detector | Setup | What it caught in our test | Choose it when |
| --- | --- | --- | --- |
| Bullet 8.2.0 | `Bullet.enable`, `Bullet.raise = true` in `config/environments/test.rb` | The `order.customer` loop in a request spec, on SQLite, with the fix in the message: `Add to your query: .includes([:customer])` | Any database, including Rails 8's default SQLite. Request specs work through its Rack middleware; model specs need `Bullet.start_request` and `Bullet.end_request` around each example |
| Prosopite 2.2.0 | `Prosopite.raise = true`, `Prosopite.scan` and `Prosopite.finish` around each example, plus the `pg_query` gem unless you use MySQL or MariaDB | The same loop on SQLite, but as `PgQuery::ParseError: syntax error at or near "LIMIT"` instead of an N+1 report | PostgreSQL or MySQL. It flags repeated identical queries, so it also catches N+1s that do not go through an association |
| `strict_loading` (built in) | `Order.strict_loading` on a relation, or `self.strict_loading_by_default = true` in a model | The loop, as `ActiveRecord::StrictLoadingViolationError`, when set on the relation. With `strict_loading_by_default = true` and `strict_loading_mode = :n_plus_one_only`, it raised for none of the loops we tried | New models and hot queries where every lazy load is a bug, including single-record ones |

For most teams, Bullet in the test environment is the first gate, with `strict_loading` on the relations behind your busiest pages:

```ruby title="config/environments/test.rb"
Rails.application.configure do
  config.after_initialize do
    Bullet.enable = true
    Bullet.bullet_logger = true
    Bullet.raise = true # an N+1 in any request spec fails that spec
  end
  # ...
end
```

The detector only fires when a spec loads more than one record, so add a collection example to every index action. Criterion 5 in the refund prompt above is that example.

**Copy-paste prompt: find and fix N+1 queries in the index actions**

```text
Bullet raises on N+1 queries in the test environment. For every controller action under app/controllers that renders a collection (index actions, and any view that iterates over an association), check spec/requests for an example that creates at least three records with the associations the view touches. Add the missing examples first and run them: each N+1 must fail with Bullet::Notification::UnoptimizedQueryError. Then fix each one with includes, preload or eager_load, choosing the one Bullet suggests unless the view filters on the association. Do not set Bullet.raise to false, do not add Bullet safelist entries, and do not change the new examples to create fewer records. Show me the Bullet messages before and the bin/rspec result after.
```

For the database side of the same problem, including `EXPLAIN` plans and indexes, see [SQL patterns](/en/cookbook/database-recipes/sql-patterns/) and [ORM patterns](/en/cookbook/database-recipes/orm-patterns/).

## How do you handle Rails migrations with an agent?

Specs alone cannot vouch for a migration: the agent can write a migration that applies cleanly to an empty test database and still locks a large table or breaks the running app during deploy. The classic case: the agent renames a column with `rename_column`, the specs pass, and the app servers still running the old code raise errors on every query that uses the old name.

`strong_migrations` turns those cases into an error at `bin/rails db:migrate` time, with the safe alternative in the message. It supports PostgreSQL, MySQL and MariaDB (not SQLite). Install it with `bundle add strong_migrations` and `bin/rails generate strong_migrations:install`. Removing a column, for example, fails with instructions to add the column to `self.ignored_columns`, deploy, and only then remove it inside `safety_assured { ... }`.

Split the rest of the work between gates and a person:

| Check | How | Who decides |
| --- | --- | --- |
| Unsafe operation | `strong_migrations` raises on the migration | CI, and the agent reads the message |
| Schema and migrations agree | `bin/rails db:migrate` on a fresh database, then `git diff --exit-code db/schema.rb` | CI |
| The newest migration is reversible | `bin/rails db:migrate:redo STEP=1` | CI (`bin/ci` and the workflow above) |
| The change is what you expect | The `db/schema.rb` diff attached to the pull request | A human reads the schema diff, not the Ruby |
| `safety_assured`, destructive or data-backfill migrations | `CODEOWNERS` on `db/migrate/` | A human |

**Copy-paste prompt: rename a column without downtime**

```text
Rename orders.notes to orders.customer_notes without downtime, as an expand-and-contract change in separate pull requests. In THIS pull request do only the expand step: generate a migration that adds customer_notes, write to both columns from the model, backfill existing rows in batches with in_batches in a separate migration, and read from customer_notes with a fallback to notes. Do not remove or rename notes and do not use safety_assured. Run bin/rails db:migrate, bin/rails db:migrate:redo STEP=1 and bin/rspec. Show me the db/schema.rb diff and list every statement that could lock the orders table, or say "none". Then write the steps for the contract pull request as a checklist in the PR description.
```

For the wider rules on expand-and-contract changes and rollbacks, see [database migration patterns](/en/cookbook/database-recipes/migration-patterns/).

## How do you know the agent's specs would catch a bug?

A green run does not tell you the specs would fail if the code were wrong, and specs written by the same agent that wrote the code are the ones most likely to share its blind spots. Mutation testing answers the question: `mutant` changes the code under test in small ways and reports every change the specs did not notice.

On the test app, one spec for `Order#large?` (`total_cents >= 10_000`) passed, and `mutant` reported 7 surviving mutations out of 18, 61.11% coverage. The first survivor was the boundary: `total_cents > 10000`. No spec checked an order of exactly 10,000 cents.

```bash
# terminal: mutation-test only the subjects changed since main
bundle exec mutant run --integration rspec --usage opensource \
  --require ./config/environment --since main -- 'Order*'
```

Add `mutant-rspec` to the `:development, :test` group with `require: false`. `mutant` is free for open-source projects (`--usage opensource`); private, commercial code needs a paid subscription and `--usage commercial`. Run it on the changed subjects rather than the whole app, because every mutation re-runs the selected specs. [Oracle strength](/en/workflows/test/oracle-strength/) explains how to turn survivors into missing examples.

**Copy-paste prompt: turn surviving mutants into missing specs**

```text
Run: bundle exec mutant run --integration rspec --usage opensource --require ./config/environment --since main -- 'Refund*' 'RefundsController*'
For each surviving mutation, decide: (A) the mutated code is equally correct and the original is redundant, or (B) a spec is missing. For every B, add one example to the existing spec file that fails against the mutated code and passes against the original. Do not change anything under app/. Re-run mutant and show me the before and after Alive counts, and list any A cases for me to decide.
```

## How do you give the agent Rails-aware code navigation?

Text search finds `def total` but not every caller of an association, a scope or a route helper. Two additions help most in Rails: a language server that understands Ruby, and an MCP server that reads routes, schema and model relationships.

**Ruby LSP.** Shopify's language server (`ruby-lsp` gem, 0.26.11) includes its Rails add-on automatically when it detects a Rails app. In Claude Code, the `ruby-lsp` plugin in the official marketplace registers it; the plugin does not bundle the binary. LSP plugins add no always-on context, because the server runs out of process.

**Rails MCP Server.** The `rails-mcp-server` gem (2.0.0) exposes three tools, `switch_project`, `search_tools` and `execute_tool`, and behind them analyzers such as `get_routes`, `get_schema` and `analyze_models`. With `--single-project` it serves the current directory without a `projects.yml`. Popularity: 261,700 total downloads on rubygems.org (read 2026-09-26). It is a community project, so read its source before you give it a production database. Its always-on tool-definition cost is small; the analyzers load only when called through `execute_tool`.

**Claude Code**

    ```bash
    # terminal
    gem install ruby-lsp
    claude plugin install ruby-lsp@claude-plugins-official
    gem install rails-mcp-server
    claude mcp add rails -- rails-mcp-server --single-project
    ```

**Codex**

    ```bash
    # terminal, from the app's root
    gem install rails-mcp-server
    codex mcp add rails -- rails-mcp-server --single-project
    ```

**Cursor**

    Add the MCP server to `.cursor/mcp.json` in the app's root:

    ```json
    { "mcpServers": { "rails": { "command": "rails-mcp-server", "args": ["--single-project"] } } }
    ```

Without them, the agent's grep for `has_many :refunds` misses a scope defined in a concern. With them, one prompt maps the blast radius first:

**Copy-paste prompt: map a change before editing**

```text
Using the rails MCP server and the language server, find every route, controller action, model scope, job and view that reads or writes orders.status. Show the list with file and line, and mark which ones have a spec that exercises them. Do not change files.
```

[Code intelligence MCP servers](/en/ecosystem/mcp/code-intelligence-mcp/) compares language-server and index-based options for larger codebases.

## What breaks when agents write Rails code?

**Prosopite reports a PgQuery::ParseError on SQLite**

Symptom: a spec fails with `PgQuery::ParseError: syntax error at or near "LIMIT"` from inside Prosopite. Cause: Prosopite fingerprints queries with `pg_query`, a PostgreSQL parser, and SQLite's `?` placeholders do not parse; the error is an N+1 in disguise (Prosopite 2.2.0, pg_query 6.2.3, checked 2026-09-26). Recovery: use Bullet on SQLite, and move to Prosopite when the app runs on PostgreSQL or MySQL.

**strict_loading is on and nothing raises**

Symptom: `config.active_record.strict_loading_mode = :n_plus_one_only` is set, and an obvious N+1 loop still passes. Cause: with strict loading on, that mode only reports some nested lazy loads; on Rails 8.1.4 it raised for none of the top-level loops we tried. Recovery: call `strict_loading` on the relation (`Order.strict_loading.includes(...)`) or keep the default `:all` mode on the models where every lazy load is a bug, and run Bullet for the rest.

**The agent edits db/schema.rb or an old migration**

Symptom: the schema looks right on the branch and production is missing a column, or a colleague's database is out of step. Cause: the agent edited the generated file instead of adding a migration. Recovery: the `git diff --exit-code db/schema.rb` step in CI catches it; re-prompt: "Revert your edits to db/schema.rb and db/migrate/*, generate a new migration for the change, run bin/rails db:migrate and commit the schema it produces."

**A migration that passes locally and fails redo**

Symptom: `bin/ci` fails on the reversible step with `ActiveRecord::IrreversibleMigration`. Cause: `remove_column` without a type, `change_column`, or an `execute` inside `change`. Recovery: "Rewrite the migration with separate up and down methods, or pass the column type to remove_column so change can reverse it. Run bin/rails db:migrate:redo STEP=1 until it passes."

**The spec changed to match the bug**

Symptom: the diff touches `spec/` in the same commit that fixes `app/`, and an expected value moved. Cause: the agent optimised for green. Recovery: put `spec/` under `CODEOWNERS`, keep the "do not modify spec/" line in every implementation prompt, and keep the "Existing specs unchanged" step from the CI job above. [Protect the oracle](/en/workflows/test/protect-the-oracle/) has the other mechanical options.

**Suppressions instead of fixes**

Symptom: the gates are green and the diff adds `# rubocop:disable`, an entry in `config/brakeman.ignore`, a Bullet safelist entry or `safety_assured`. Recovery: give those files and patterns a human owner in `CODEOWNERS` and re-prompt: "Remove the suppression you added and fix the underlying offense. If it is a false positive, explain why in the pull request instead."

## Where to go next with Rails and agents

- [Protect the oracle](/en/workflows/test/protect-the-oracle/) — Stop agents from editing the specs that judge them.
- [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) — Expand-and-contract changes and rollbacks for the migrations above.
- [API development patterns](/en/cookbook/backend-recipes/api-patterns/) — Idempotency keys, pagination and contracts for the endpoints you build.
- [Python workflow recipes](/en/cookbook/backend-recipes/python-patterns/) — The same gates and loops for Django and FastAPI.
- [Evidence bundle](/en/workflows/ship/evidence-bundle/) — Attach gate results and the schema diff so the reviewer checks proof, not code.
- [Agent-ready codebase](/en/workflows/harness/agent-ready-codebase/) — The repository properties that make any agent more reliable.
