Testing Rails
Rails ships with Minitest; most production teams use RSpec. The framework matters far less than three decisions: what layer a test sits at, how data is created, and how much of the real stack the test exercises. Getting those wrong is how a suite becomes slow and useless at the same time.
The 60-second answer
Section titled “The 60-second answer”“Tests are layered by cost and confidence. Model specs are fast and cover rules and scopes. Request specs go through routing, middleware and the controller and assert status and side effects — they replaced controller specs, which RSpec removed. System specs drive a real browser through Capybara and are the only ones that catch Turbo, JavaScript and form-wiring bugs, at ten to a hundred times the cost. FactoryBot builds records; create writes to the database and build does not, so use build unless persistence is the point. The test database is separate, built from schema.rb, and by default each example runs in a transaction that is rolled back, so tests are isolated without truncating tables.”
The test database is built from db/schema.rb. Edit a migration without re-running db:migrate and the test database drifts, producing failures nobody can reproduce.
Factories
Section titled “Factories”post = build(:post) # not savedpost = create(:post, :published) # savedposts = create_list(:post, 3)Rules that keep factories useful: only required attributes in the base factory (every optional one is data every test carries), traits for variants, one association per factory (cascading factories create dozens of rows per example), and build_stubbed when a record only needs an id.
Model specs
Section titled “Model specs”RSpec.describe Post do it "requires a title" do expect(build(:post, title: nil)).not_to be_valid end
describe ".published" do it "excludes drafts" do published = create(:post, :published) create(:post)
expect(described_class.published).to contain_exactly(published) end endendTest behaviour, not implementation: assert that published excludes drafts, not that it calls where.not(published_at: nil). Implementation assertions break on every refactor and catch nothing.
Request specs
Section titled “Request specs”RSpec.describe "Posts" do describe "POST /posts" do it "creates a post and redirects" do expect { post posts_path, params: { post: { title: "Hello", body: "World" } } }.to change(Post, :count).by(1)
expect(response).to redirect_to(post_path(Post.last)) end
it "re-renders the form with 422 when invalid" do post posts_path, params: { post: { title: "" } }
expect(response).to have_http_status(:unprocessable_entity) expect(response.body).to include("can't be blank") end endendRequest specs exercise routing, filters and rendering, which is where the bugs are. Assert status and observable effect; assert the body only for content that matters.
System specs
Section titled “System specs”RSpec.describe "Creating a post", type: :system do before { driven_by(:cuprite) } # or :selenium_chrome_headless
it "shows the new post without a full reload" do visit new_post_path fill_in "Title", with: "Turbo works" click_on "Create Post"
expect(page).to have_content("Turbo works") endendUse system specs for JavaScript behaviour, Turbo Frames and Streams, multi-step forms and authentication flows. Do not use them for validation messages — a model spec covers that at 1% of the cost. A suite with two hundred system specs runs for twenty minutes and gets skipped.
Transactional tests
Section titled “Transactional tests”use_transactional_fixtures = true wraps each example in a transaction and rolls it back: fast, because nothing is truncated. It breaks in exactly one situation — code using a second database connection cannot see the first connection’s uncommitted rows. That means a separate job worker process, or a browser server that does not share the connection.
- Keep transactions on for everything except where a separate process is involved.
- For jobs, prefer
perform_enqueued_jobs(in-process) over a real worker in tests. - Otherwise switch those specs to truncation (
DatabaseCleaner) and accept the slowdown.
What not to test
Section titled “What not to test”- Framework behaviour. That
belongs_tovalidates presence is Rails’ test, not yours. - Getters and trivial delegations. That is a test of Ruby.
- Private methods. Test them through the public API; if you cannot, the object has no purpose.
- Exact HTML structure.
have_selector("div.card > h2")breaks on every CSS change; assert text and behaviour. - Every branch of a callback. Test the outcome the callback exists to produce.
Follow-up questions
Section titled “Follow-up questions”- Why are request specs preferred over controller specs?
- When does a transactional test fail, and what do you do about it?
- When would you use
build_stubbed? - How do you test a job that calls an external API?
- How do you keep a large suite fast?
Common traps
Section titled “Common traps”createeverywhere. Cascading factories create fifty rows per example and the suite takes minutes to prove nothing.- Sleeping in system specs.
sleep 2is a flaky test; use Capybara’s waiting matchers. - Testing implementation.
expect(post).to receive(:save)breaks on refactor and proves nothing. - Skipping
db:test:prepare. Failures that only exist on your machine. - No tests for the failure path. The 422 render is the branch that breaks in production.