Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl. For older versions, use FactoryGirl
instead of FactoryBot
.
FactoryBot.define do
factory :user do
first_name { 'John' }
last_name { 'Doe' }
birthdate { 21.years.ago }
admin { false }
sequence(:username) { |n| "user#{n}" }
end
end
See: Defining factories
factory :user, class: 'User' do
···
end
factory :user, aliases: [:author] do
···
end
factory :post do
association :author, factory: :user
association :author, factory: [:user, :admin]
end
factory :post do
author # assumes there's a factory :author
end
factory :post do
after :create do |post|
create :theme, post: post # has_one
create_list :comment, 3, post: post # has_many
end
end
factory :user do
first_name { 'John' }
factory :sample_user do
first_name { FFaker::Name.first_name }
end
end
create :sample_user
See: Inheritance
factory :user do
···
end
factory :sample_user, parent: :user do
first_name { FFaker::Name.first_name }
end
create :sample_user
Works the same as nested factories.
factory :user do
transient do
upcased { true }
end
after :create do |user, options|
user.name.upcase! if options.upcased
end
end
create(user, upcased: true)
Transient attributes will not get passed to the model, but will be available in after-create hooks.
See: Transient attributes