skip to content

A Rails suite using factory_bot slowed down because create(:line_item) inserts a chain of parent records; how do you find the cascade and cut it?

level: seniorimportance: should knowfreq 38%

answer

  1. every association can mean another INSERT
  2. subscribe to factory_bot.run_factory
  3. before_run_factory gives the call stack
  4. share parents: create_list(..., order: order)
  5. build_stubbed where nothing is read back

basics

~20 s

Count factory runs per name and strategy by subscribing to factory_bot.run_factory (and before_run_factory for the call stack), then pass shared parents into create_list, move optional associations into traits, and use build or build_stubbed where no row is needed.

solid answer

~40 s

Each declared association in factory_bot runs another factory, so with `create` one `create(:line_item)` can insert a line item, an order, a customer, a product and a band. `create_list(:line_item, 20)` multiplies that by twenty, because each item gets its own order. To measure it, I subscribe to the `factory_bot.run_factory` notification and tally `payload[:name]` and `payload[:strategy]` over a run. factory_bot 6.6 added `factory_bot.before_run_factory`, so pairing the two events gives a call stack showing who triggered which parent. The fixes: pass the shared parent (`create_list(:line_item, 20, order: order)`); keep base factories to required associations and move the rest into traits; use `build`, which builds its associations because `use_parent_strategy` is true, or `build_stubbed` where the test never reads the row back; and drop `after(:create)` graphs from base factories.

code

ruby · 11 lines
ruby
# Before: 20 orders, 20 customers, 20 products, 20 bands
create_list(:line_item, 20)

# After: one of each parent
order   = create(:order)
product = create(:product)
create_list(:line_item, 20, order: order, product: product)

# A presenter test that never reads rows back
item = build_stubbed(:line_item)
assert_equal "2 x Tour Hoodie", LineItemPresenter.new(item).label

go deeper

for a junior

Know that each association in a factory can create another record, and that passing a parent into create_list avoids duplicates.

for a middle

Explain how use_parent_strategy decides what build and create do to associations, and when build_stubbed is enough.

for a senior

Measure factory runs with the instrumentation events, cut the biggest cascades first, and guard factories with FactoryBot.lint in CI.

for a principal

Treat suite runtime as a budget: decide which factory changes, test-data conventions and checks keep it from creeping back.

## Why the cascade happens In factory_bot, every declared association (`order`, `product`, `association :customer`) runs another factory when the object is made. With `create`, that factory creates too, and its own associations follow: - `create(:line_item)` runs the `:order` and `:product` factories with `create`. - `create(:order)` in turn creates its `:customer`. - `create(:product)` in turn creates its `:band`. One call writes five rows. `create_list(:line_item, 20)` writes up to a hundred, because each line item gets its **own** order and product unless you pass them in. Add an `after(:create)` in the base `:order` factory that creates three line items, and every `create(:order)` anywhere in the suite pays for it. ## Measuring before cutting factory_bot publishes `ActiveSupport::Notifications` events for every run: - **`factory_bot.run_factory`** wraps each factory run; its payload has `:name`, `:strategy`, `:traits`, `:overrides` and `:factory`. - **`factory_bot.before_run_factory`**, added in factory_bot 6.6, fires before a run starts. Pushing on it and popping on `run_factory` gives a call stack, so you can see that `:band` was created by `:product`, which was created by `:line_item`. ```ruby counts = Hash.new(0) ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |event| counts[[event.payload[:name], event.payload[:strategy]]] += 1 end at_exit { pp counts.sort_by { |_, n| -n }.first(10) } ``` The top of that list, usually a `create` of a deep parent like `:band`, is where the time goes. The event duration (`event.duration`) shows which single factories are slow. ## Cutting it | Change | Effect | |---|---| | `create_list(:line_item, 20, order: order, product: product)` | one order and one product instead of twenty of each | | move optional associations into traits | base `create(:order)` writes only what validations need | | `build(:line_item)` | builds the parents too, because `use_parent_strategy` is `true`; no rows | | `build_stubbed(:line_item)` | stubbed parents, fake ids, no connection at all | | remove `after(:create)` children from base factories | callers opt in with `:with_line_items` | | `build_list(:line_item, 20, order: order)` | twenty unsaved items for code that only sums or formats them | ## Traps when fixing 1. **`use_parent_strategy = false`** in an old suite makes `build` create its associations. Check `FactoryBot.use_parent_strategy` before assuming `build` is free. 2. **Uniqueness collisions.** Sharing one product across twenty line items is fine, but forcing shared customers through a global variable couples tests. Pass parents explicitly in each test. 3. **Validations needing saved parents.** `belongs_to` is required by default, but that validation only checks the association is present. A built parent satisfies it with `build`, while `create` of the child saves the parent first. 4. **Stubbed records and queries.** `build_stubbed` objects have fake ids, so any code that queries for their children finds nothing. ## Keeping it fixed - Run `FactoryBot.lint` in CI. It creates every factory, and optionally every trait with `traits: true`, inside a transaction that is rolled back, and raises `FactoryBot::InvalidFactoryError` listing the factories that no longer save. - Keep a short budget in the factory instrumentation, such as a warning when one factory run exceeds half a second. - Review new `after(:create)` hooks the way you would review N+1 queries: they multiply. ## Reading the numbers When the tally comes back, look for three patterns: 1. **A deep parent with a huge `create` count**, such as `[:band, :create]` at 40,000 in a suite of 3,000 tests. Something near the top of the chain is creating it implicitly; the call stack from `before_run_factory` shows which factory. 2. **A `create` count far above the `build` count** for factories used mostly in model and presenter tests. These tests can usually switch strategy without other changes. 3. **One slow factory** with few calls but a long duration. That is usually an `after(:create)` hook that attaches files or creates large collections, and belongs in a trait. Fix the largest number first, re-run the tally, and stop when the suite time stops falling. A few shared parents and strategy changes typically remove most of the cascade without touching the tests' meaning.

  • Why does FactoryBot.lint not leave rows behind in the test database?
    The linter wraps each factory or trait run in `ActiveRecord::Base.transaction(joinable: false)` and raises `ActiveRecord::Rollback` at the end, so everything it created is rolled back. It collects the failures and raises `FactoryBot::InvalidFactoryError` with the list.
  • When is association :band, strategy: :build the wrong fix for a slow product factory?
    When the product must be saved and its `band_id` must point at a real row, for example with a database foreign key or code that queries the band. Saving the product still inserts the built band, because Active Record saves a new `belongs_to` target before the child unless the association says `autosave: false`, so the option saves almost nothing. Sharing one created band across products is the cleaner cut.

  • build(:line_item) always inserts its parents, whatever the configuration.
  • create_list(:line_item, 20) shares one order across all twenty items.
  • Moving associations into traits makes create(:order) invalid by design.
  • factory_bot has no way to report which factories run most often.
  • build_stubbed records can safely load their has_many children from the database.

Assumes factory_bot 6.6 (factory_bot.before_run_factory is new in 6.6) via factory_bot_rails 6.5 on Rails 8.1.