Skip to content

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.

“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.

post = build(:post) # not saved
post = create(:post, :published) # saved
posts = 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.

spec/models/post_spec.rb
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
end
end

Test 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.

spec/requests/posts_spec.rb
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
end
end

Request 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.

spec/system/post_creation_spec.rb
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")
end
end

Use 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.

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.
  • Framework behaviour. That belongs_to validates 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.
  1. Why are request specs preferred over controller specs?
  2. When does a transactional test fail, and what do you do about it?
  3. When would you use build_stubbed?
  4. How do you test a job that calls an external API?
  5. How do you keep a large suite fast?
  • create everywhere. Cascading factories create fifty rows per example and the suite takes minutes to prove nothing.
  • Sleeping in system specs. sleep 2 is 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.