Home

Faster Specs Without Faster Machines

· 2 min read

When a Rails test suite gets slow, the instinct is to throw hardware at it: more CI workers, more parallelism, bigger machines. That helps, but it hides the real problem.

Profile a slow suite and you usually find the same thing. The tests aren't doing anything expensive. They're doing something cheap, over and over. Creating a company, a user, a chart of accounts, a few products, again for every single example.

Measure first

TestProf makes the waste visible. FPROF=1 shows which factories run most often and how many records they create behind your back. The answer is almost always surprising.

FPROF=1 bundle exec rspec spec/models

Create once, reuse everywhere

The biggest win is let_it_be. It creates a record once for the whole group, inside a transaction that rolls back at the end, instead of once per example.

# before: one company per example
let!(:company) { create(:company) }

# after: one company per group
let_it_be(:company) { create(:company) }

The catch is that the record is shared, so a test that changes it can leak into the next one. Use let_it_be(..., reload: true) when a test mutates state, and keep the plain let for anything a test really needs fresh.

Then the smaller wins

  • Factory defaults — stop every association from building its own parent company.
  • build over create — if a test never touches the database, don't make it.
  • before_all — for setup that isn't a single record.

None of this is clever. It's just refusing to pay for the same work twice. A fast suite isn't a luxury, it's what decides whether people actually run the tests before pushing.