Test Factories
Every test needs objects to act on, and how you make them decides whether the suite stays readable and fast or turns into a swamp of fixture files nobody dares edit. This guide covers why we use factory_bot, how to set it up with RSpec, the day-to-day API — build strategies, traits, associations, sequences, transients — and the habits that keep a suite quick as the schema grows.
1. Why Factories Over Fixtures
Rails fixtures are a global, shared dataset: every test sees the same
users.yml, so the record one test needs is the record another test
is counting, and a change to a fixture ripples through specs that never
mention it. Factories flip that around. Each test declares the
objects it needs, right where it needs them, and gets fresh ones nobody
else can touch.
The discipline that makes this work is the minimal valid record: a
factory defines only what the model needs to be valid, and every
other attribute is opt-in at the call site. When a spec reads
create(:user, :admin, name: "Ada"), everything that matters to that
spec is on that line — and nothing that doesn't matter is hiding in a
file three directories away.
2. Installation
Add factory_bot_rails to the development and test group so the
generators know to create factory files, then include the syntax
methods in RSpec so you can write create(:user) instead of
FactoryBot.create(:user):
# Gemfile
group :development, :test do
gem "factory_bot_rails"
end# spec/support/factory_bot.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
endFactories live in spec/factories/, one file per model, and
factory_bot_rails loads them automatically. A first factory looks
like this — note that every attribute is a block, so values are
evaluated fresh for each record:
# spec/factories/users.rb
FactoryBot.define do
factory :user do
name { "Ada Lovelace" }
email { generate(:email) }
end
endA generated rails_helper.rb has the spec/support glob commented out.
Uncomment Rails.root.glob("spec/support/**/*.rb").sort.each { |f| require f }
(or add the include directly to rails_helper.rb) or the syntax methods
silently won't be there.
3. Build Strategies
Four verbs make objects from a factory, and choosing the cheapest one that satisfies the test is the single biggest lever on suite speed. They all accept the same traits and attribute overrides.
| Verb | What it touches | Reach for it when |
|---|---|---|
build(:user)
| Nothing — an unsaved instance | Unit tests of methods that don't need an id or persisted associations. |
create(:user)
| The database | Anything that queries, joins, or relies on callbacks and constraints actually running. |
build_stubbed(:user)
| Nothing — but the object claims to be persisted | The fastest option for view, presenter, and component specs: it has an id and |
attributes_for(:user)
| Nothing — returns a Hash | Request specs: the params hash for a POST or PATCH. |
Each verb has a _list form (create_list(:user, 3)) and a _pair
form. Overrides are a trailing hash, and a block receives the object
after it is built:
user = build(:user, name: "Grace") # unsaved
admins = create_list(:user, 2, :admin) # saved, with a trait
params = attributes_for(:user) # { name: "...", email: "..." }
create(:user) do |user|
user.posts.create!(attributes_for(:post))
end4. Traits
A trait is a named bundle of attributes that describes a variation of
the record — :admin, :expired, :with_avatar. They replace the two
ways factories go wrong: one enormous factory that sets everything, and
a pile of boolean flags (admin: true, active: true, verified: true)
that every spec has to get right in combination.
# spec/factories/subscriptions.rb
FactoryBot.define do
factory :subscription do
user
plan { "starter" }
expires_at { 1.month.from_now }
trait :expired do
expires_at { 1.day.ago }
end
trait :enterprise do
plan { "enterprise" }
seats { 50 }
end
end
endcreate(:subscription, :expired)
create(:subscription, :enterprise, :expired, seats: 12) # traits compose; overrides winTraits are listed as symbols before the overrides hash, compose in any combination, and work with every build strategy. If you find yourself passing the same three traits together everywhere, that is a new trait.
5. Associations and Sequences
Writing the association's name on its own line — the bare user in the
subscription factory above — builds it from the :user factory using
the same strategy as the parent: build(:subscription) builds an
unsaved user, create(:subscription) creates one. That default (since
factory_bot 5) is what keeps build from quietly hitting the database
through its associations. Point at a different factory or trait with
association:
factory :subscription do
association :user, factory: [:user, :admin] # explicit factory + trait
endSequences exist for uniqueness constraints. A factory that hardcodes
email { "ada@example.com" } works exactly once per test; a sequence
hands out a fresh value every time it is asked:
# spec/factories/sequences.rb
FactoryBot.define do
sequence(:email) { |n| "person#{n}@example.com" }
end
# Or inline, scoped to one factory:
factory :user do
sequence(:username) { |n| "user_#{n}" }
end6. Transient Attributes and Callbacks
A transient attribute is a factory input that is not a model
attribute. Combined with after(:build) / after(:create) callbacks it
lets a factory take instructions — "give this list three items" —
without the spec having to build the items itself:
# spec/factories/lists.rb
FactoryBot.define do
factory :list do
title { "Groceries" }
transient do
items_count { 0 }
end
after(:create) do |list, evaluator|
create_list(:item, evaluator.items_count, list: list)
list.reload
end
end
endcreate(:list) # no items
create(:list, items_count: 3) # three items, associated and reloadedThe callback receives the record and an evaluator holding every
attribute including the transient ones. Transients are ignored by
attributes_for (they aren't model attributes), and an after(:create)
callback only fires for create — if the variation has to work with
build and build_stubbed too, prefer an inline association list
(items { [association(:item)] }), which every strategy honors.
7. Suite Speed and Hygiene
Factories are the easiest way to make a suite slow, because the cost is invisible at the call site. Three habits keep it in check.
Persist only when persistence is the point. A spec of a model
method, a presenter, or a component rarely needs a database row. Reach
for build or build_stubbed first and step up to create when the
test actually queries. Across hundreds of examples this is the
difference between seconds and minutes.
Watch for association explosions. A create(:comment) that builds a
post, which builds an author, which builds an organization, which
builds a billing plan, quietly inserts half the schema per example.
Keep required associations minimal in the factory, and lean on
build_stubbed where the chain doesn't matter.
Lint the factories. A factory that no longer produces a valid
record fails every spec that uses it, usually with a message about the
spec rather than the factory. FactoryBot.lint builds every factory
(and, with traits: true, every trait) and reports the broken ones by
name. Run it as a rake task in CI rather than before(:suite), so
single-spec runs stay fast:
# lib/tasks/factory_bot.rake
namespace :factory_bot do
desc "Verify that every factory and trait builds a valid record"
task lint: :environment do
if Rails.env.test?
ActiveRecord::Base.transaction do
FactoryBot.lint traits: true
raise ActiveRecord::Rollback
end
else
system("bundle exec rake factory_bot:lint RAILS_ENV=test") || abort
end
end
endbundle exec rake factory_bot:lint
8. When a Factory Is Overkill
Factories describe persistable records with validity rules. Not every object a test needs is one of those:
- A plain Ruby object — a value object, a form object, a service's
input — is clearer constructed directly:
Money.new(1200, "USD")says more thanbuild(:money)ever will. - A params hash for a request spec is often just a literal hash. Use
attributes_forwhen the factory already knows the valid shape; write the hash when the spec is about the shape. - A one-off record with unusual attributes belongs in the spec as overrides, not as a new factory or trait nobody else will use.
The question to ask is whether the next reader learns more from the factory name or from the literal. Factories earn their keep when the same valid record is needed in many places; the rest of the time, plain Ruby wins.
Success!
Your test data is declared where it is used, minimal by default, and as fast as each spec allows. Before you move on: