3 category: Ruby libraries
8 - "FactoryBot.define do"
11 - "sequence(:username) { |n| \"user#{n}\" }"
14 [Factory Bot](http://www.rubydoc.info/gems/factory_bot/) is a helper for writing factories for Ruby tests.
15 It was previously known as Factory Girl. For older versions, use `FactoryGirl` instead of `FactoryBot`.
21 ### Defining factories
28 birthdate { 21.years.ago }
31 sequence(:username) { |n| "user#{n}" }
37 See: [Defining factories](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Defining_factories)
41 #### Custom class names
44 factory :user, class: 'User' do
52 factory :user, aliases: [:author] do
62 FactoryBot.build(:user)
68 build(:user) # → model (not saved)
69 create(:user) # → model (saved)
70 attributes_for(:user) # → hash
71 build_stubbed(:user) # stubbed out attributes
77 build(:user, name: 'John')
93 association :author, factory: :user
94 association :author, factory: [:user, :admin]
103 author # assumes there's a factory :author
107 ### After-create hooks
111 after :create do |post|
112 create :theme, post: post # has_one
113 create_list :comment, 3, post: post # has_many
131 {: data-line="2,3,4"}
137 Traits allow you to group attributes together.
138 See: [Traits](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Traits)
146 factory :sample_user do
147 first_name { FFaker::Name.first_name }
151 {: data-line="4,5,6"}
157 See: [Inheritance](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Inheritance)
168 factory :sample_user, parent: :user do
169 first_name { FFaker::Name.first_name }
178 Works the same as nested factories.
180 ### Options (transients)
188 after :create do |user, options|
189 user.name.upcase! if options.upcased
193 {: data-line="2,3,4"}
196 create(user, upcased: true)
199 Transient attributes will not get passed to the model, but will be available in after-create hooks.
200 See: [Transient attributes](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Transient_Attributes)
206 * test/factories/*.rb
207 * spec/factories/*.rb
209 Place your factories in these locations.
215 * <http://rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md>