FactoryBot: build vs. create, Overrides & Traits
FactoryBot (formerly Factory Girl) generates test data via a factory pattern, replacing Rails' built-in static YAML fixtures with a flexible, code-based approach supporting dynamic values and per-test overrides.
Defining a Factory
FactoryBot.define do
factory :user do
name { "Ada Lovelace" }
sequence(:email) { |n| "user#{n}@example.com" }
trait :admin do
role { "admin" }
end
end
end
# sequence() gives each generated user a unique email,
# avoiding uniqueness-constraint failures across testsbuild vs. create
user = FactoryBot.build(:user) # in-memory only, not saved -- faster
user = FactoryBot.create(:user) # saved to the database
# Prefer build() whenever the test doesn't actually need
# the record persisted -- skips an unnecessary DB writeOverrides & Traits
FactoryBot.create(:user, name: "Bob") # override a specific attribute
FactoryBot.create(:user, :admin) # apply the :admin trait
FactoryBot.create_list(:user, 5) # create 5 independent usersWhy Not Just `Model.new(...)` Everywhere?
When a model gains a new required attribute, a shared factory only needs updating once. Tests manually instantiating objects everywhere would each need individual updates -- a real maintenance burden a shared factory avoids.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free