FactoryBot: Associations, Callbacks & Best Practices
Associations
factory :post do
title { "My Post" }
association :author, factory: :user
end
# Creating a :post automatically creates the related :user too,
# mirroring the model's actual belongs_to associationWatching Association Overhead
If every test creating a Post also creates a full User (and that User's own associations), the cumulative database writes across hundreds of tests can meaningfully slow the suite down -- worth being deliberate about which associations actually auto-create.
Callbacks
factory :user do
name { "Ada" }
after(:create) do |user|
create(:profile, user: user)
end
end
# Runs additional setup once the base object is actually created --
# useful for coordinated multi-object setupFactory Inheritance
factory :admin_user, parent: :user do
role { "admin" }
end
# Cleanly layers on top of :user's defaults instead of
# cramming conditional logic into one large factoryPairing With Faker
factory :user do
name { Faker::Name.name }
email { Faker::Internet.email }
end
# Varied, realistic random data can surface edge cases that
# a single hardcoded test value would never revealKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free