skip to content

For a Rails test suite, when do YAML fixtures beat factory_bot factories, and when do factories win?

level: middleimportance: must knowfreq 58%

answer

  1. Rails ships fixtures by default
  2. fixtures: loaded once, rolled back
  3. factories: data built inside each test
  4. fixtures skip validations; create runs save!
  5. mixing: reference data plus scenarios

basics

~20 s

Fixtures win on speed and shared, named reference data, since they load once and roll back; factories win when each test needs its own explicit, valid variations, at the cost of inserts in every test and possible cascades.

solid answer

~40 s

A new Rails 8.1 app uses Minitest with fixtures. `fixtures :all` loads the YAML once per run and every test rolls back, so the per-test cost is close to zero and tests share a named world: `products(:tour_hoodie)`. The costs are hidden setup, since the data a test depends on lives in another file, and rows that bypass validations. factory_bot puts the data inside the test: `create(:order, :paid)` says exactly what matters, traits express variations, and `create` goes through `save!`, so records are valid. Its costs are inserts in every test and association cascades that slow suites down. My rule: fixtures for stable reference data and the common happy path, factories where a test needs a specific variation. Many teams combine them, with fixtures for products and bands and factories for orders.

code

ruby · 10 lines
ruby
# Fixture style: data lives in test/fixtures/orders.yml
test "a paid order cannot be cancelled" do
  assert_not orders(:paid_last_week).cancellable?
end

# Factory style: the relevant facts are in the test
test "a paid order cannot be cancelled" do
  order = build(:order, :paid)
  assert_not order.cancellable?
end

go deeper

for a junior

Know that Rails ships with fixtures, that factory_bot is the common alternative, and what each looks like in a test.

for a middle

Compare the cost models: load-once and rollback versus per-test inserts, and skipped versus enforced validations.

for a senior

Choose per table and per test, combine both deliberately, and guard each side with validity checks and cascade limits.

for a principal

Set a suite-wide test-data strategy that balances runtime, readability and the coupling of shared data across teams.

## Two ways to get test data **YAML fixtures** are Rails' built-in answer: rows written in `test/fixtures/*.yml`, loaded by `fixtures :all` and read with accessors such as `products(:tour_hoodie)`. **factory_bot**, through the `factory_bot_rails` gem, is the common alternative: Ruby definitions in `test/factories/*.rb` (or `spec/factories`) that build objects on demand with `build`, `create` or `build_stubbed`. ## Cost model | Aspect | Fixtures | factory_bot | |---|---|---| | When rows are written | once, before the first test (per process) | inside every test that calls `create` | | Per-test database cost | a transaction begin and rollback | one insert per created object, plus its parents | | Validations and callbacks | skipped (raw SQL insert) | run on `create` (`save!`) | | Where setup is visible | in YAML files, away from the test | in the test body, through traits and overrides | | Variations | another labelled row, seen by every test | a trait or an override, local to one test | | Shared state risk | tests start to depend on rows added for others | low, since data is per test | ## Where fixtures win - **Speed at scale.** Thousands of tests reusing a few hundred rows pay the insert cost once. Rails' own generators and guides assume them. - **Stable reference data.** Bands, product categories, shipping zones and the admin user are the same in every test, and named labels read well: `bands(:night_owls)`. - **Zero dependencies.** No gem, no factory maintenance, and the generated tests (`bin/rails generate model`) already use them. ## Where factories win - **Explicit scenarios.** `create(:order, :paid, :with_line_items, line_items_count: 2)` puts the facts the test depends on in the test. - **Many small variations.** A refund rule tested against ten order states needs ten traits or overrides, not ten global fixture rows. - **Valid by construction.** Because `create` calls `save!`, a factory that drifts from the model's validations fails loudly, and `FactoryBot.lint` can check them all. ## Costs to watch on each side 1. **Fixture coupling.** Counting rows (`Order.count`) or relying on a label's incidental attributes breaks when someone edits a shared row. 2. **Invalid fixtures.** Rows bypass validations, so a model test that validates every fixture is a cheap guard. 3. **Factory cascades.** Each association can insert a chain of parents; `create_list` multiplies it. 4. **Slow defaults.** `create` everywhere, when `build` or `build_stubbed` would do, is the usual reason factory suites are slower than fixture suites. ## A combined setup Mixing is common and supported: keep `fixtures :all` for reference tables and include `FactoryBot::Syntax::Methods` for scenario data. A factory can point at a fixture row: ```ruby factory :order do customer shipping_zone { ShippingZone.find_by!(code: "eu") } # from fixtures end ``` The rule of thumb many teams use is that **nouns that rarely change are fixtures, and situations a test is about are factories**. Neither choice is wrong. The decision is about where your suite's time and clarity problems are. ## Moving an existing suite Switching wholesale is rarely worth it. A gradual path works better: 1. Add `factory_bot_rails` and include `FactoryBot::Syntax::Methods`, leaving `fixtures :all` in place. 2. Write **new** tests with factories where they need variations; keep fixtures for reference tables. 3. When a fixture row exists only to serve one test, delete it and build that record inside the test instead. 4. Watch suite time as you go. If it climbs, look for `create` calls that could be `build` and for factory cascades before blaming the approach. 5. Keep one owner per table: a table seeded by fixtures should not also get conflicting rows from a factory default, or tests will see both. ## What interviewers listen for A strong answer names concrete costs on both sides, such as load-once speed against hidden coupling, or explicit setup against per-test inserts. It does not declare one tool simply better.

  • Can factory_bot and YAML fixtures be used in the same Rails test suite?
    Yes. `fixtures :all` keeps loading the YAML, and including `FactoryBot::Syntax::Methods` adds `create` and friends. Teams often keep reference tables as fixtures and build scenario records with factories, sometimes looking fixture rows up inside a factory. Keep one source of truth per table so the two do not disagree.
  • Why does adding factory_bot_rails stop Rails from generating fixture files?
    factory_bot_rails registers itself as the generators' fixture replacement. In a Minitest app it sets `fixture: false, fixture_replacement: :factory_bot`, so `bin/rails generate model Order` writes `test/factories/orders.rb` instead of `test/fixtures/orders.yml`. `config.generators { |g| g.factory_bot false }` turns that off.

  • Factories are always faster than fixtures because nothing is preloaded.
  • Fixtures run model validations as they are loaded, so they are always valid.
  • You must remove fixtures :all before using factory_bot.
  • Fixtures are reinserted before every test, so they cost the same as factories.
  • A factory created with create can hold a row that fails validation.