๐ญ
FactoryBot
Clean test data generation
FactoryBot is a library for generating test data.
# spec/factories/users.rb
FactoryBot.define do
factory :user do
name { 'Test User' }
email { Faker::Internet.email } # Random data with Faker gem
password { 'password123' }
trait :admin do
after(:create) { |user| user.add_role(:admin) }
end
trait :with_posts do
after(:create) do |user|
create_list(:post, 3, user: user)
end
end
end
end
Usage:
create(:user) # save to DB
build(:user) # in-memory only (no save)
create(:user, :admin) # apply trait
create(:user, name: 'Custom') # override attribute
create_list(:user, 5) # create 5
Fixture vs Factory:
Fixture: fixed data in YAML files (Rails default)
Factory: dynamic data creation in code (more flexible)
Key Points
1
Create factory definition files in spec/factories/ directory
2
Define default attributes with factory :model do ... end block
3
Define variants with trait :name do ... end (admin, with_posts, etc.)
4
create(:model) โ create DB-persisted instance
5
build(:model) โ create non-persisted instance (fast)
6
association โ auto-creates related models
Pros
- ✓ Defined in code โ flexible and dynamic
- ✓ Easy variant management with traits
- ✓ Auto association handling
- ✓ Realistic data combined with Faker gem
Cons
- ✗ Hard to manage when factories get complex
- ✗ Overusing create slows tests (build recommended)
- ✗ Watch out for circular references
- ✗ Implicit association creation can cause confusion
Use Cases
RSpec test data generation
Create role-based users with traits
Auto-create relationship data with associations
Bulk data creation with create_list