3 category: Ruby libraries
8 - "FactoryBot.define do"
11 - "sequence(:username) { |n| \"user#{n}\" }"
21 [Factory Bot](http://www.rubydoc.info/gems/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`.
23 - [Factory Bot documentation](http://www.rubydoc.info/gems/factory_bot/) _(rubydoc.info)_
24 - [Getting started](https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md) _(github.com)_
25 - [Source code](https://github.com/thoughtbot/factory_bot) _(github.com)_
27 ### Defining factories
34 birthdate { 21.years.ago }
37 sequence(:username) { |n| "user#{n}" }
43 See: [Defining factories](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Defining_factories)
47 #### Custom class names
50 factory :user, class: 'User' do
58 factory :user, aliases: [:author] do
68 FactoryBot.build(:user)
74 build(:user) # → model (not saved)
75 create(:user) # → model (saved)
76 attributes_for(:user) # → hash
77 build_stubbed(:user) # stubbed out attributes
83 build(:user, name: 'John')
99 association :author, factory: :user
100 association :author, factory: [:user, :admin]
109 author # assumes there's a factory :author
113 ### After-create hooks
117 after :create do |post|
118 create :theme, post: post # has_one
119 create_list :comment, 3, post: post # has_many
137 {: data-line="2,3,4"}
143 Traits allow you to group attributes together.
144 See: [Traits](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Traits)
150 first_name { 'John' }
152 factory :sample_user do
153 first_name { FFaker::Name.first_name }
157 {: data-line="4,5,6"}
163 See: [Inheritance](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Inheritance)
174 factory :sample_user, parent: :user do
175 first_name { FFaker::Name.first_name }
184 Works the same as nested factories.
186 ### Options (transients)
194 after :create do |user, options|
195 user.name.upcase! if options.upcased
199 {: data-line="2,3,4"}
202 create(user, upcased: true)
205 Transient attributes will not get passed to the model, but will be available in after-create hooks.
206 See: [Transient attributes](http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Transient_Attributes)
212 * test/factories/*.rb
213 * spec/factories/*.rb
215 Place your factories in these locations.
221 * <http://rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md>