Intro

factory_bot is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance.

Its documentation is split as such:

  • the guide is a great place to start for first-time users.
  • the cookbook is the go-to place for creative solutions to common situations.
  • the wiki details considerations for integrating with other software.
  • the reference is terse facts for those who use this project often.

License

factory_bot is Copyright © 2008 Joe Ferris and thoughtbot. It is free software, and may be redistributed under the terms specified in the LICENSE file.

About thoughtbot

factory_bot is maintained and funded by thoughtbot, inc. The names and logos for thoughtbot are trademarks of thoughtbot, inc.

We love open source software! See our other projects or hire us to design, develop, and grow your product.

Build strategies

Once a factory_bot factory is defined, it can be constructed using any of the built-in build strategies, or a custom build strategy.

All of these strategies notify on the factory_bot.run_factory instrumentation using ActiveSupport::Notifications, passing a payload with :name, :strategy, :traits, :overrides, and :factory keys.

The non-list (.build, .build_pair, .create, etc.) methods take one mandatory argument: the name of the factory. They can then optionally take names of traits, and then a hash of attributes to override. Finally, they can take a block. This block takes the produced object as an argument, and returns an updated object.

The list methods (.build_list, .create_list, etc.) have two required arguments: the name of the factory, and the number of instances to build. They then can optionally take traits and overrides. Finally, they can take a block. This block takes the produced object and the zero-based index as arguments, and returns an updated object.

build

The FactoryBot.build method constructs an instance of the class according to initialize_with, which defaults to calling the .new class method. .build_list constructs multiple instances, and .build_pair is a shorthand to construct two instances.

After it calls initialize_with, it invokes the after_build hook.

Associations are constructed using the build build strategy.

create

The FactoryBot.create method constructs an instance of the class according to initialize_with, and then persists it using to_create. The .create_list class method constructs multiple instances, and .create_pair is a shorthand to construct two instances.

After it calls initialize_with, it invokes the following hooks in order:

  1. after_build
  2. before_create
  3. non-hook: to_create
  4. after_create

Associations are constructed using the create build strategy.

The to_create hook controls how objects are persisted. It takes a block with the object and the factory_bot context, and runs it for its side effect. By default, it calls #save!.

attributes_for

The FactoryBot.attributes_for method constructs a Hash with the attributes and their values, using initialize_with. The attributes_for_pair and attributes_for_list methods work similarly as build_pair and build_list.

Associations are constructed using the null build strategy (they are not built).

No hooks are called.

build_stubbed

The FactoryBot.build_stubbed method returns a fake ActiveRecord object. The .build_stubbed_pair and .build_stubbed_list methods are defined similarly to .build_pair and .build_list.

It uses initialize_with to construct the object, but then stubs methods and data as appropriate:

  • id is set sequentially (unless overridden by attributes)
  • created_at and updated_at are set to the current time (unless overridden by attributes)
  • all ActiveModel::Dirty change tracking is cleared
  • persisted? is true
  • new_record? is false
  • destroyed? is false
  • persistence methods raise a RuntimeError (#connection, #delete, #save, #update, etc.)

After it sets up the object it invokes the after_stub hook.

null

The FactoryBot.null method returns nil. The .null_pair method gives you a pair of nils, and .null_list gives as many nils as you desire. This is used internally.

FactoryBot.find_definitions

The FactoryBot.find_definitions method loads in all factory_bot definitions across the project.

The load order is controlled by the FactoryBot.definition_file_paths attribute. The default load order is:

  1. factories.rb
  2. test/factories.rb
  3. test/factories/**/*.rb
  4. spec/factories.rb
  5. spec/factories/**/*.rb

Rails

The .find_definitions method is called automatically by factory_bot_rails after initialize. The .definition_file_paths can be set during initialization (e.g. config/initializers), or via Rails.application.config.factory_bot.definition_file_paths.

FactoryBot.define

Each file loaded by factory_bot is expected to call FactoryBot.define with a block. The block is evaluated within an instance of FactoryBot::Syntax::Default::DSL, giving access to factory, sequence, trait, and other methods.

factory

Within a FactoryBot.define block, you can define factories. Anything defined using factory can be built using a build strategy.

The factory method takes three arguments: a required name, an optional hash of options, and an optional block.

The name is expected to be a Symbol.

Options

  • :class - what class to construct. This can be either a class, or a String or Symbol (anything that responds to #to_s). By default it is either the parent's class name or the factory's name.
  • :parent- the name of another factory that this factory should inherit from. Defaults to nil.
  • :aliases - alternative names for this factory. Any of these names can be used with a build strategy. Defaults to the empty list.
  • :traits - base traits that are used by default when building this factory. Defaults to the empty list.

Block

You can use the block to define your factory. Within here you have access to the following methods:

You can use factory inside a factory block to define a new factory with an implied parent.

add_attribute

Within a factory definition, the add_attribute method defines a key/value pair that will be set when the object is built.

The add_attribute method takes two arguments: a name (Symbol or String) and a block. This block is called each time this object is constructed. The block is not called when the attribute is overriden by a build strategy.

Assignment is done by calling the Ruby attribute setter. For example, given

FactoryBot.define do
  factory :user do
    add_attribute(:name) { "Acid Burn" }
  end
end

This will use the #name= setter:

user = User.new
user.name = "Acid Burn"

Also see method_missing for a shorthand.

association

Within a factory block, use the association method to always make an additional object alongside this one. This name best makes sense within the context of ActiveRecord.

The association method takes a mandatory name and optional options.

The options are zero or more trait names (Symbols), followed by a hash of attribute overrides. When constructing this association, factory_bot uses the trait and attribute overrides given.

See method_missing for a shorthand. See build strategies for an explanation of how each build strategy handles associations.

sequence

A factory_bot set up supports two levels of sequences: global and factory-specific.

Global sequences

With a Factory.define block, use the sequence method to define global sequences that can be shared with other factories.

The sequence method takes a name, optional arguments, and a block. The name is expected to be a Symbol.

The supported arguments are a number representing the starting value (default: 1), and :aliases (default []). The starting value must respond to #next.

The block takes a value as an argument, and returns a result.

The sequence value is incremented globally. Using an :email_address sequence from multiple places increments the value each time.

See method_missing for a shorthand.

Factory sequences

Sequences can be localized within factory blocks. The syntax is the same as for a global sequence, but the scope of the incremented value is limited to the factory definition.

In addition, using sequence with a factory block implicitly calls add_attribute for that value.

These two are similar, except the second example does not cause any global sequences to exist:

# A global sequence
sequence(:user_factory_email) { |n| "person#{n}@example.com" }

factory :user do
  # Using a global sequence
  email { generate(:user_factory_email) }
end
# A factory-scoped sequence
factory :user do
  sequence(:email) { |n| "person#{n}@example.com" }
end

trait

Within a factory definition block, use the trait method to define named permutations of the factory.

The trait method takes a name (Symbol) and a block. Treat the block like you would a factory definition block.

See method_missing for a shorthand.

method_missing

With a factory definition block, you can use add_attribute, association, sequence, and trait to define a factory. You can also level a default method_missing definition for potential shortcuts.

Calling an unknown method (e.g. name, admin, email, account) connects an association, sequence, trait, or attribute to the factory:

  1. If the method missing is passed a block, it always defines an attribute. This allows you to set the value for the attribute.

  2. If the method missing is passed a hash as a argument with the key :factory, then it always defines an association. This allows you to override the factory used for the association.

  3. If there is another factory of the same name, then it defines an association.

  4. If there is a global sequence of the same name, then it defines an attribute with a value that pulls from the sequence.

  5. If there is a trait of the same name for that factory, then it turns that trait on for all builds of this factory.

Using method_missing can turn an explicit definition:

FactoryBot.define do
  sequence(:email) { |n| "person#{n}@example.com" }
  factory :account
  factory :organization

  factory :user, traits: [:admin] do
    add_attribute(:name) { "Lord Nikon" }
    add_attribute(:email) { generate(:email) }
    association :account
    association :org, factory: :organization

    trait :admin do
      add_attribute(:admin) { true }
    end
  end
end

... into a more implicit definition:

FactoryBot.define do
  sequence(:email) { |n| "person#{n}@example.com" }
  factory :account
  factory :organization

  factory :user do
    name { "Lord Nikon" }      # no more `add_attribute`
    admin                      # no more :traits
    email                      # no more `add_attribute`
    account                    # no more `association`
    org factory: :organization # no more `association`

    trait :admin do
      admin { true }
    end
  end
end

traits_for_enum

With a factory definition block, the traits_for_enum method is a helper for any object with an attribute that can be one of a few values. The original inspiration was ActiveRecord::Enum but it can apply to any attribute with a restricted set of values.

This method creates a trait for each value.

The traits_for_enum method takes a required attribute name and an optional set of values. The values can be any Enumerable, such as Array or Hash. By default, the values are nil.

If the values are an Array, this method defines a trait for each element in the array. The trait's name is the array element, and it sets the attribute to the same array element.

If the values are a Hash, this method defines traits based on the keys, setting the attribute to the values. The trait's name is the key, and it sets the attribute to the value.

If the value is any other Enumerable, it treats it like an Array or Hash based on whether #each iterates in pairs like it does for Hashes.

If the value is nil, it uses a class method named after the pluralized attribute name.

FactoryBot.define do
  factory :article do
    traits_for_enum :visibility, [:public, :private]
    # trait :public do
    #   visibility { :public }
    # end
    # trait :private do
    #   visibility { :private }
    # end

    traits_for_enum :collaborative, draft: 0, shared: 1
    # trait :draft do
    #   collaborative { 0 }
    # end
    # trait :shared do
    #   collaborative { 1 }
    # end

    traits_for_enum :status
    # Article.statuses.each do |key, value|
    #   trait key do
    #     status { value }
    #   end
    # end
  end
end

skip_create, to_create, and initialize_with

The skip_create, to_create, and initialize_with methods control how factory_bot interacts with the build strategies.

These methods can be called within a factory definition block, to scope their effects to just that factory; or within FactoryBot.define, to affect global change.

initialize_with

The initialize_with method takes a block and returns an instance of the factory's class. It has access to the attributes method, which is a hash of all the fields and values for the object.

The default definition is:

initialize_with { new }

to_create

The to_create method lets you control the FactoryBot.create strategy. This method takes a block which takes the object as constructed by initialize_with, and the factory_bot context. The context has additional data from any transient blocks.

The default definition is:

to_create { |obj, context| obj.save! }

The skip_create method is a shorthand for turning to_create into a no-op. This allows you to use the create strategy as a synonym for build, except you additionally get any create hooks.

transient

Within a factory definition block, the goal is to construct an instance of the class. While factory_bot does this, it keeps track of data in a context. To set data on this context, use a transient block.

Treat a transient block like a factory definition block. However, none of the attributes, associations, traits, or sequences you set will impact the final object.

This is most useful when paired with hooks or to_create.

Hooks

Within a factory definition block and the FactoryBot.define block, you have access to the after, before, and callback methods. This allow you to hook into parts of the build strategies.

Within a factory definition block, these callbacks are scoped to just that factory. Within a FactoryBot.define block, they are global to all factories.

callback

The callback method allows you to hook into any factory_bot callback by name. The pre-defined names, as seen in the build strategies reference, are after_build, before_create, after_create, and after_stub.

This method takes a splat of names, and a block. It invokes the block any time one of the names is activated. The block can be anything that responds to #to_proc.

This block takes two arguments: the instance of the factory, and the factory_bot context. The context holds transient attributes.

The same callback name can be hooked into multiple times. Every block is run, in the order it was defined. Callbacks are inherited from their parents; the parents' callbacks are run first.

after and before methods

The after and before methods add some nice syntax to callback:

after(:create) do |user, context|
  user.post_first_article(context.article)
end

callback(:after_create) do |user, context|
  user.post_first_article(context.article)
end

FactoryBot.modify

The FactoryBot.modify class method defines a block with an overriding factory method available. That is the only method you can call within the block.

The factory method within this block takes a mandatory factory name, and a block. All other arguments are ignored. The factory name must already be defined. The block is a normal factory definition block. Take note that hooks cannot be cleared and continue to compound.

For details on why you'd want to use this, see the guide.

FactoryBot.lint

The FactoryBot.lint method tries each factory and raises FactoryBot::InvalidFactoryError on failure.

It can take the following optional arguments:

  • A splat of factory names. This will restrict the linting to just the ones listed. The default is all.
  • :strategy - the build strategy to use. The default is :create.
  • :traits - whether to try building each trait, too. The default is false.
  • :verbose - whether to show a stack trace on error. The default is false.

Suggested techniques for hooking .lint into your system is discussed in the guide.

FactoryBot.register_strategy

The FactoryBot.register_strategy method is how to add a build strategy.

It takes two mandatory arguments: name and class. The name is a Symbol, and registering it exposes a method under FactoryBot::Syntax::Methods.

The class must define the methods association and result.

The association method takes an instance of FactoryRunner. You can #run this runner, passing a strategy name (it defaults to the current one) and an optional block. The block is called after the association is built, and is passed the object that was built.

The result method takes the object that was built for this factory (using initalize_with), and returns the result of this factory for this build strategy.

Setup

Installation varies based on the framework you are using, if any, and optionally the test framework.

Since installation varies based on code that we do not control, those docs are kept up-to-date in our wiki. We encourage you to edit the wiki as the frameworks change.

Below we document the most common setup. However, we go into more detail in our wiki.

Update Your Gemfile

If you're using Rails:

gem "factory_bot_rails"

If you're not using Rails:

gem "factory_bot"

For more, see our wiki.

Configure your test suite

RSpec

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

Test::Unit

class Test::Unit::TestCase
  include FactoryBot::Syntax::Methods
end

For more, see our wiki.

Using Without Bundler

If you're not using Bundler, be sure to have the gem installed and call:

require 'factory_bot'

Once required, assuming you have a directory structure of spec/factories or test/factories, all you'll need to do is run:

FactoryBot.find_definitions

If you're using a separate directory structure for your factories, you can change the definition file paths before trying to find definitions:

FactoryBot.definition_file_paths = %w(custom_factories_directory)
FactoryBot.find_definitions

If you don't have a separate directory of factories and would like to define them inline, that's possible as well:

require 'factory_bot'

FactoryBot.define do
  factory :user do
    name { 'John Doe' }
    date_of_birth { 21.years.ago }
  end
end

Rails Preloaders and RSpec

When running RSpec with a Rails preloader such as spring or zeus, it's possible to encounter an ActiveRecord::AssociationTypeMismatch error when creating a factory with associations, as below:

FactoryBot.define do
  factory :united_states, class: "Location" do
    name { 'United States' }
    association :location_group, factory: :north_america
  end

  factory :north_america, class: "LocationGroup" do
    name { 'North America' }
  end
end

The error occurs during the run of the test suite:

Failure/Error: united_states = create(:united_states)
ActiveRecord::AssociationTypeMismatch:
  LocationGroup(#70251250797320) expected, got LocationGroup(#70251200725840)

The two possible solutions are to either run the suite without the preloader, or to add FactoryBot.reload to the RSpec configuration, like so:

RSpec.configure do |config|
  config.before(:suite) { FactoryBot.reload }
end

Defining factories

Factory name and attributes

Each factory has a name and a set of attributes. The name is used to guess the class of the object by default:

# This will guess the User class
FactoryBot.define do
  factory :user do
    first_name { "John" }
    last_name  { "Doe" }
    admin { false }
  end
end

Specifying the class explicitly

It is also possible to explicitly specify the class:

# This will use the User class (otherwise Admin would have been guessed)
factory :admin, class: "User"

You can pass a constant as well, if the constant is available (note that this can cause test performance problems in large Rails applications, since referring to the constant will cause it to be eagerly loaded).

factory :access_token, class: User

Definition file paths

Factories can be defined anywhere, but will be automatically loaded after calling FactoryBot.find_definitions if factories are defined in files at the following locations:

test/factories.rb
spec/factories.rb
test/factories/*.rb
spec/factories/*.rb

Hash attributes

Because of the block syntax in Ruby, defining attributes as Hashes (for serialized/JSON columns, for example) requires two sets of curly brackets:

factory :program do
  configuration { { auto_resolve: false, auto_define: true } }
end

Alternatively you may prefer do/end syntax:

factory :program do
  configuration do
    { auto_resolve: false, auto_define: true }
  end
end

However, defining a value as a hash makes it complicated to set values within the hash when constructing an object. Instead, prefer to use factory_bot itself:

factory :program do
  configuration { attributes_for(:configuration) }
end

factory :configuration do
  auto_resolve { false }
  auto_define { true }
end

This way you can more easily set value when building:

create(
  :program,
  configuration: attributes_for(
    :configuration,
    auto_resolve: true,
  )
)

Best practices

It is recommended that you have one factory for each class that provides the simplest set of attributes necessary to create an instance of that class. If you're creating ActiveRecord objects, that means that you should only provide attributes that are required through validations and that do not have defaults. Other factories can be created through inheritance to cover common scenarios for each class.

Attempting to define multiple factories with the same name will raise an error.

Static Attributes

Static attributes (without a block) are no longer available in factory_bot 5. You can read more about the decision to remove them in this blog post.

Using factories

Build strategies

factory_bot supports several different build strategies: build, create, attributes_for and build_stubbed:

# Returns a User instance that's not saved
user = build(:user)

# Returns a saved User instance
user = create(:user)

# Returns a hash of attributes, which can be used to build a User instance for example
attrs = attributes_for(:user)

# Integrates with Ruby 3.0's support for pattern matching assignment
attributes_for(:user) => {email:, name:, **attrs}

# Returns an object with all defined attributes stubbed out
stub = build_stubbed(:user)

# Passing a block to any of the methods above will yield the return object
create(:user) do |user|
  user.posts.create(attributes_for(:post))
end

build_stubbed and Marshal.dump

Note that objects created with build_stubbed cannot be serialized with Marshal.dump, since factory_bot defines singleton methods on these objects.

Building or Creating Multiple Records

Sometimes, you'll want to create or build multiple instances of a factory at once.

built_users   = build_list(:user, 25)
created_users = create_list(:user, 25)

These methods will build or create a specific amount of factories and return them as an array. To set the attributes for each of the factories, you can pass in a hash as you normally would.

twenty_year_olds = build_list(:user, 25, date_of_birth: 20.years.ago)

In order to set different attributes for each factory, these methods may be passed a block, with the factory and the index as parameters:

twenty_somethings = build_list(:user, 10) do |user, i|
  user.date_of_birth = (20 + i).years.ago
end

create_list passes saved instances into the block. If you modify the instance, you must save it again:

twenty_somethings = create_list(:user, 10) do |user, i|
  user.date_of_birth = (20 + i).years.ago
  user.save!
end

build_stubbed_list will give you fully stubbed out instances:

stubbed_users = build_stubbed_list(:user, 25) # array of stubbed users

There's also a set of *_pair methods for creating two records at a time:

built_users   = build_pair(:user) # array of two built users
created_users = create_pair(:user) # array of two created users

If you need multiple attribute hashes, attributes_for_list will generate them:

users_attrs = attributes_for_list(:user, 25) # array of attribute hashes

Attribute overrides

No matter which strategy is used, it's possible to override the defined attributes by passing a hash:

# Build a User instance and override the first_name property
user = build(:user, first_name: "Joe")
user.first_name
# => "Joe"

Ruby 3.1's support for omitting values from Hash literals dovetails with attribute overrides and provides an opportunity to limit the repetition of variable names:

first_name = "Joe"

# Build a User instance and override the first_name property
user = build(:user, first_name:)
user.first_name
# => "Joe"

Aliases

factory_bot allows you to define aliases to existing factories to make them easier to re-use. This could come in handy when, for example, your Post object has an author attribute that actually refers to an instance of a User class. While normally factory_bot can infer the factory name from the association name, in this case it will look for an author factory in vain. So, alias your user factory so it can be used under alias names.

factory :user, aliases: [:author, :commenter] do
  first_name { "John" }
  last_name { "Doe" }
  date_of_birth { 18.years.ago }
end

factory :post do
  # The alias allows us to write author instead of
  # association :author, factory: :user
  author
  title { "How to read a book effectively" }
  body { "There are five steps involved." }
end

factory :comment do
  # The alias allows us to write commenter instead of
  # association :commenter, factory: :user
  commenter
  body { "Great article!" }
end

Dependent Attributes

Attributes can be based on the values of other attributes using the context that is yielded to dynamic attribute blocks:

factory :user do
  first_name { "Joe" }
  last_name  { "Blow" }
  email { "#{first_name}.#{last_name}@example.com".downcase }
end

create(:user, last_name: "Doe").email
# => "joe.doe@example.com"

Transient Attributes

Transient attributes are attributes only available within the factory definition, and not set on the object being built. This allows for more complex logic inside factories.

These are defined within a transient block:

factory :user do
  name { "Zero Cool" }
  birth_date { age&.years.ago }

  transient do
    age { 11 } # only used to set `birth_date` above
  end
end

With other attributes

You can access transient attributes within other attributes (see Dependent Attributes):

factory :user do
  transient do
    rockstar { true }
  end

  name { "John Doe#{" - Rockstar" if rockstar}" }
end

create(:user).name
#=> "John Doe - ROCKSTAR"

create(:user, rockstar: false).name
#=> "John Doe"

With attributes_for

Transient attributes will be ignored within attributes_for and won't be set on the model, even if the attribute exists or you attempt to override it.

With callbacks

If you need to access the evaluated definition itself in a factory_bot callback, you'll need to declare a second block argument (for the definition) and access transient attributes from there. This represents the final, evaluated value.

factory :user do
  transient do
    upcased { false }
  end

  name { "John Doe" }

  after(:create) do |user, context|
    user.name.upcase! if context.upcased
  end
end

create(:user).name
#=> "John Doe"

create(:user, upcased: true).name
#=> "JOHN DOE"

With associations

Transient associations are not supported in factory_bot. Associations within the transient block will be treated as regular, non-transient associations.

If needed, you can generally work around this by building a factory within a transient attribute:

factory :post

factory :user do
  transient do
    post { build(:post) }
  end
end

Method Name / Reserved Word Attributes

If your attributes conflict with existing methods or reserved words (all methods in the DefinitionProxy class) you can define them with add_attribute.

factory :dna do
  add_attribute(:sequence) { 'GATTACA' }
end

factory :payment do
  add_attribute(:method) { 'paypal' }
end

Inheritance

Nested factories

You can create multiple factories for the same class without repeating common attributes by nesting factories:

factory :post do
  title { "A title" }

  factory :approved_post do
    approved { true }
  end
end

approved_post = create(:approved_post)
approved_post.title    # => "A title"
approved_post.approved # => true

Assigning parent explicitly

You can also assign the parent explicitly:

factory :post do
  title { "A title" }
end

factory :approved_post, parent: :post do
  approved { true }
end

Best practices

As mentioned above, it's good practice to define a basic factory for each class with only the attributes required to create it. Then, create more specific factories that inherit from this basic parent.

Associations

Implicit definition

It's possible to set up associations within factories. If the factory name is the same as the association name, the factory name can be left out.

factory :post do
  # ...
  author
end

Explicit definition

You can define associations explicitly. This can be handy especially when Overriding attributes

factory :post do
  # ...
  association :author
end

Inline definition

You can also define associations inline within regular attributes, but note that the value will be nil when using the attributes_for strategy.

factory :post do
  # ...
  author { association :author }
end

Specifying the factory

You can specify a different factory (although Aliases might also help you out here).

Implicitly:

factory :post do
  # ...
  author factory: :user
end

Explicitly:

factory :post do
  # ...
  association :author, factory: :user
end

Inline:

factory :post do
  # ...
  author { association :user }
end

Overriding attributes

You can also override attributes on associations.

Implicitly:

factory :post do
  # ...
  author factory: :author, last_name: "Writely"
end

Explicitly:

factory :post do
  # ...
  association :author, last_name: "Writely"
end

Or inline using attributes from the factory:

factory :post do
  # ...
  author_last_name { "Writely" }
  author { association :author, last_name: author_last_name }
end

Association overrides

Attribute overrides can be used to link associated objects:

FactoryBot.define do
  factory :author do
    name { 'Taylor' }
  end

  factory :post do
    author
  end
end

eunji = build(:author, name: 'Eunji')
post = build(:post, author: eunji)

Ruby 3.1's support for omitting values from Hash literals dovetails with attribute overrides, and provides an opportunity to limit the repetition of variable names:

author = build(:author, name: 'Eunji')

post = build(:post, author:)

Build strategies

Associations default to using the same build strategy as their parent object:

FactoryBot.define do
  factory :author

  factory :post do
    author
  end
end

post = build(:post)
post.new_record?        # => true
post.author.new_record? # => true

post = create(:post)
post.new_record?        # => false
post.author.new_record? # => false

This is different than the default behavior for previous versions of factory_bot, where the association strategy would not always match the strategy of the parent object. If you want to continue using the old behavior, you can set the use_parent_strategy configuration option to false.

FactoryBot.use_parent_strategy = false

# Builds and saves a User and a Post
post = create(:post)
post.new_record?        # => false
post.author.new_record? # => false

# Builds and saves a User, and then builds but does not save a Post
post = build(:post)
post.new_record?        # => true
post.author.new_record? # => false

To not save the associated object, specify strategy: :build in the factory:

FactoryBot.use_parent_strategy = false

factory :post do
  # ...
  association :author, factory: :user, strategy: :build
end

# Builds a User, and then builds a Post, but does not save either
post = build(:post)
post.new_record?        # => true
post.author.new_record? # => true

Note that the strategy: :build option must be passed to an explicit call to association, and cannot be used with implicit associations:

factory :post do
  # ...
  author strategy: :build    # <<< this does *not* work; causes author_id to be nil

Sequences

Global sequences

Unique values in a specific format (for example, e-mail addresses) can be generated using sequences. Sequences are defined by calling sequence in a definition block, and values in a sequence are generated by calling generate:

# Defines a new sequence
FactoryBot.define do
  sequence :email do |n|
    "person#{n}@example.com"
  end
end

generate :email
# => "person1@example.com"

generate :email
# => "person2@example.com"

With dynamic attributes

Sequences can be used in dynamic attributes:

FactoryBot.define do
  sequence :email do |n|
    "person#{n}@example.com"
  end
end

factory :invite do
  invitee { generate(:email) }
end

As implicit attributes

Or as implicit attributes:

FactoryBot.define do
  sequence :email do |n|
    "person#{n}@example.com"
  end
end

factory :user do
  email # Same as `email { generate(:email) }`
end

Note that defining sequences as implicit attributes will not work if you have a factory with the same name as the sequence.

Inline sequences

And it's also possible to define an in-line sequence that is only used in a particular factory:

factory :user do
  sequence(:email) { |n| "person#{n}@example.com" }
end

With Ruby 2.7's support for numbered parameters, inline definitions can be even more abbreviated:

factory :user do
  sequence(:email) { "person#{_1}@example.com" }
end

Initial value

You can override the initial value. Any value that responds to the #next method will work (e.g. 1, 2, 3, 'a', 'b', 'c')

factory :user do
  sequence(:email, 1000) { |n| "person#{n}@example.com" }
end

Without a block

Without a block, the value will increment itself, starting at its initial value:

factory :post do
  sequence(:position)
end

Note that the value for the sequence could be any Enumerable instance, as long as it responds to #next:

factory :task do
  sequence :priority, %i[low medium high urgent].cycle
end

Aliases

Sequences can also have aliases. The sequence aliases share the same counter:

factory :user do
  sequence(:email, 1000, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
end

# will increase value counter for :email which is shared by :sender and :receiver
generate(:sender)

Define aliases and use default value (1) for the counter

factory :user do
  sequence(:email, aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
end

Setting the value:

factory :user do
  sequence(:email, 'a', aliases: [:sender, :receiver]) { |n| "person#{n}@example.com" }
end

The value needs to support the #next method. Here the next value will be 'a', then 'b', etc.

Rewinding

Sequences can also be rewound with FactoryBot.rewind_sequences:

sequence(:email) {|n| "person#{n}@example.com" }

generate(:email) # "person1@example.com"
generate(:email) # "person2@example.com"
generate(:email) # "person3@example.com"

FactoryBot.rewind_sequences

generate(:email) # "person1@example.com"

This rewinds all registered sequences.

Uniqueness

When working with uniqueness constraints, be careful not to pass in override values that will conflict with the generated sequence values.

In this example the email will be the same for both users. If email must be unique, this code will error:

factory :user do
  sequence(:email) { |n| "person#{n}@example.com" }
end

FactoryBot.create(:user, email: "person1@example.com")
FactoryBot.create(:user)

Traits

Traits allow you to group attributes together and then apply them to any factory.

factory :user, aliases: [:author]

factory :story do
  title { "My awesome story" }
  author

  trait :published do
    published { true }
  end

  trait :unpublished do
    published { false }
  end

  trait :week_long_publishing do
    start_at { 1.week.ago }
    end_at { Time.now }
  end

  trait :month_long_publishing do
    start_at { 1.month.ago }
    end_at { Time.now }
  end

  factory :week_long_published_story,    traits: [:published, :week_long_publishing]
  factory :month_long_published_story,   traits: [:published, :month_long_publishing]
  factory :week_long_unpublished_story,  traits: [:unpublished, :week_long_publishing]
  factory :month_long_unpublished_story, traits: [:unpublished, :month_long_publishing]
end

As implicit attributes

Traits can be used as implicit attributes:

factory :week_long_published_story_with_title, parent: :story do
  published
  week_long_publishing
  title { "Publishing that was started at #{start_at}" }
end

Note that defining traits as implicit attributes will not work if you have a factory or sequence with the same name as the trait.

Using traits

Traits can also be passed in as a list of Symbols when you construct an instance from factory_bot.

factory :user do
  name { "Friendly User" }

  trait :active do
    name { "John Doe" }
    status { :active }
  end

  trait :admin do
    admin { true }
  end
end

# creates an admin user with :active status and name "Jon Snow"
create(:user, :admin, :active, name: "Jon Snow")

This ability works with build, build_stubbed, attributes_for, and create.

create_list and build_list methods are supported as well. Remember to pass the number of instances to create/build as second parameter, as documented in the "Building or Creating Multiple Records" section of this file.

factory :user do
  name { "Friendly User" }

  trait :active do
    name { "John Doe" }
    status { :active }
  end

  trait :admin do
    admin { true }
  end
end

# creates 3 admin users with :active status and name "Jon Snow"
create_list(:user, 3, :admin, :active, name: "Jon Snow")

Enum traits

Given an Active Record model with an enum attribute:

class Task < ActiveRecord::Base
  enum status: {queued: 0, started: 1, finished: 2}
end

factory_bot will automatically define traits for each possible value of the enum:

FactoryBot.define do
  factory :task
end

FactoryBot.build(:task, :queued)
FactoryBot.build(:task, :started)
FactoryBot.build(:task, :finished)

Writing the traits out manually would be cumbersome, and is not necessary:

FactoryBot.define do
  factory :task do
    trait :queued do
      status { :queued }
    end

    trait :started do
      status { :started }
    end

    trait :finished do
      status { :finished }
    end
  end
end

If automatically defining traits for enum attributes on every factory is not desired, it is possible to disable the feature by setting FactoryBot.automatically_define_enum_traits = false

In that case, it is still possible to explicitly define traits for an enum attribute in a particular factory:

FactoryBot.automatically_define_enum_traits = false

FactoryBot.define do
  factory :task do
    traits_for_enum(:status)
  end
end

It is also possible to use this feature for other enumerable values, not specifically tied to Active Record enum attributes.

With an array:

class Task
  attr_accessor :status
end

FactoryBot.define do
  factory :task do
    traits_for_enum(:status, ["queued", "started", "finished"])
  end
end

Or with a hash:

class Task
  attr_accessor :status
end

FactoryBot.define do
  factory :task do
    traits_for_enum(:status, { queued: 0, started: 1, finished: 2 })
  end
end

Attribute precedence

Traits that define the same attributes won't raise AttributeDefinitionErrors; the trait that defines the attribute last gets precedence.

factory :user do
  name { "Friendly User" }
  login { name }

  trait :active do
    name { "John Doe" }
    status { :active }
    login { "#{name} (active)" }
  end

  trait :inactive do
    name { "Jane Doe" }
    status { :inactive }
    login { "#{name} (inactive)" }
  end

  trait :admin do
    admin { true }
    login { "admin-#{name}" }
  end

  factory :active_admin,   traits: [:active, :admin]   # login will be "admin-John Doe"
  factory :inactive_admin, traits: [:admin, :inactive] # login will be "Jane Doe (inactive)"
end

In child factories

You can override individual attributes granted by a trait in a child factory:

factory :user do
  name { "Friendly User" }
  login { name }

  trait :active do
    name { "John Doe" }
    status { :active }
    login { "#{name} (M)" }
  end

  factory :brandon do
    active
    name { "Brandon" }
  end
end

As mixins

Traits can be defined outside of factories and used as mixins to compose shared attributes:

FactoryBot.define do
  trait :timestamps do
    created_at { 8.days.ago }
    updated_at { 4.days.ago }
  end
  
  factory :user, traits: [:timestamps] do
    username { "john_doe" }
  end
  
  factory :post do
    timestamps
    title { "Traits rock" }
  end
end

With associations

Traits can be used with associations easily too:

factory :user do
  name { "Friendly User" }

  trait :admin do
    admin { true }
  end
end

factory :post do
  association :user, :admin, name: 'John Doe'
end

# creates an admin user with name "John Doe"
create(:post).user

When you're using association names that are different than the factory:

factory :user do
  name { "Friendly User" }

  trait :admin do
    admin { true }
  end
end

factory :post do
  association :author, :admin, factory: :user, name: 'John Doe'
  # or
  association :author, factory: [:user, :admin], name: 'John Doe'
end

# creates an admin user with name "John Doe"
create(:post).author

Traits within traits

Traits can be used within other traits to mix in their attributes.

factory :order do
  trait :completed do
    completed_at { 3.days.ago }
  end

  trait :refunded do
    completed
    refunded_at { 1.day.ago }
  end
end

With transient attributes

Traits can accept transient attributes.

factory :invoice do
  trait :with_amount do
    transient do
      amount { 1 }
    end

    after(:create) do |invoice, context|
      create :line_item, invoice: invoice, amount: context.amount
    end
  end
end

create :invoice, :with_amount, amount: 2

Callbacks

factory_bot makes four callbacks available:

  • after(:build) - called after a factory is built (via FactoryBot.build, FactoryBot.create)
  • before(:create) - called before a factory is saved (via FactoryBot.create)
  • after(:create) - called after a factory is saved (via FactoryBot.create)
  • after(:stub) - called after a factory is stubbed (via FactoryBot.build_stubbed)

Examples:

# Define a factory that calls the generate_hashed_password method after the user factory is built
factory :user do
  after(:build) { |user, context| generate_hashed_password(user) }
end

Note that you'll have an instance of the object in the block.

Multiple callbacks

You can also define multiple types of callbacks on the same factory:

factory :user do
  after(:build)  { |user| do_something_to(user) }
  after(:create) { |user| do_something_else_to(user) }
end

Factories can also define any number of the same kind of callback. These callbacks will be executed in the order they are specified:

factory :user do
  after(:create) { this_runs_first }
  after(:create) { then_this }
end

Calling create will invoke both after_build and after_create callbacks.

Also, like standard attributes, child factories will inherit (and can also define) callbacks from their parent factory.

Multiple callbacks can be assigned to run a block; this is useful when building various strategies that run the same code (since there are no callbacks that are shared across all strategies).

factory :user do
  callback(:after_stub, :before_create) { do_something }
  after(:stub, :create) { do_something_else }
  before(:create, :custom) { do_a_third_thing }
end

Global callbacks

To override callbacks for all factories, define them within the FactoryBot.define block:

FactoryBot.define do
  after(:build) { |object| puts "Built #{object}" }
  after(:create) { |object| AuditLog.create(attrs: object.attributes) }

  factory :user do
    name { "John Doe" }
  end
end

Symbol#to_proc

You can call callbacks that rely on Symbol#to_proc:

# app/models/user.rb
class User < ActiveRecord::Base
  def confirm!
    # confirm the user account
  end
end

# spec/factories.rb
FactoryBot.define do
  factory :user do
    after :create, &:confirm!
  end
end

create(:user) # creates the user and confirms it

Modifying factories

If you're given a set of factories (say, from a gem developer) but want to change them to fit into your application better, you can modify that factory instead of creating a child factory and adding attributes there.

If a gem were to give you a User factory:

FactoryBot.define do
  factory :user do
    full_name { "John Doe" }
    sequence(:username) { |n| "user#{n}" }
    password { "password" }
  end
end

Instead of creating a child factory that added additional attributes:

FactoryBot.define do
  factory :application_user, parent: :user do
    full_name { "Jane Doe" }
    date_of_birth { 21.years.ago }
    health { 90 }
  end
end

You could modify that factory instead.

FactoryBot.modify do
  factory :user do
    full_name { "Jane Doe" }
    date_of_birth { 21.years.ago }
    health { 90 }
  end
end

When modifying a factory, you can change any of the attributes you want (aside from callbacks).

FactoryBot.modify must be called outside of a FactoryBot.define block as it operates on factories differently.

A caveat: you can only modify factories (not sequences or traits), and callbacks still compound as they normally would. So, if the factory you're modifying defines an after(:create) callback, you defining an after(:create) won't override it, it will instead be run after the first callback.

Linting Factories

factory_bot allows for linting known factories:

FactoryBot.lint

FactoryBot.lint creates each factory and catches any exceptions raised during the creation process. FactoryBot::InvalidFactoryError is raised with a list of factories (and corresponding exceptions) for factories which could not be created.

Recommended usage of FactoryBot.lint is to run this in a separate task before your test suite is executed. Running it in a before(:suite) will negatively impact the performance of your tests when running single tests.

Example Rake task:

# lib/tasks/factory_bot.rake
namespace :factory_bot do
  desc "Verify that all FactoryBot factories are valid"
  task lint: :environment do
    if Rails.env.test?
      conn = ActiveRecord::Base.connection
      conn.transaction do
        FactoryBot.lint
        raise ActiveRecord::Rollback
      end
    else
      system("bundle exec rake factory_bot:lint RAILS_ENV='test'")
      fail if $?.exitstatus.nonzero?
    end
  end
end

After calling FactoryBot.lint, you'll likely want to clear out the database, as records will most likely be created. The provided example above uses an SQL transaction and rollback to leave the database clean.

You can lint factories selectively by passing only factories you want linted:

factories_to_lint = FactoryBot.factories.reject do |factory|
  factory.name =~ /^old_/
end

FactoryBot.lint factories_to_lint

This would lint all factories that aren't prefixed with old_.

Traits can also be linted. This option verifies that each and every trait of a factory generates a valid object on its own. This is turned on by passing traits: true to the lint method:

FactoryBot.lint traits: true

This can also be combined with other arguments:

FactoryBot.lint factories_to_lint, traits: true

You can also specify the strategy used for linting:

FactoryBot.lint strategy: :build

Verbose linting will include full backtraces for each error, which can be helpful for debugging:

FactoryBot.lint verbose: true

Custom Construction

If you want to use factory_bot to construct an object where some attributes are passed to initialize or if you want to do something other than simply calling new on your build class, you can override the default behavior by defining initialize_with on your factory. Example:

# user.rb
class User
  attr_accessor :name, :email

  def initialize(name)
    @name = name
  end
end

# factories.rb
sequence(:email) { |n| "person#{n}@example.com" }

factory :user do
  name { "Jane Doe" }
  email

  initialize_with { new(name) }
end

build(:user).name # Jane Doe

Although factory_bot is written to work with ActiveRecord out of the box, it can also work with any Ruby class. For maximum compatibility with ActiveRecord, the default initializer builds all instances by calling new on your build class without any arguments. It then calls attribute writer methods to assign all the attribute values. While that works fine for ActiveRecord, it actually doesn't work for almost any other Ruby class.

You can override the initializer in order to:

  • Build non-ActiveRecord objects that require arguments to initialize
  • Use a method other than new to instantiate the instance
  • Do wild things like decorate the instance after it's built

When using initialize_with, you don't have to declare the class itself when calling new; however, any other class methods you want to call will have to be called on the class explicitly.

For example:

factory :user do
  name { "John Doe" }

  initialize_with { User.build_with_name(name) }
end

You can also access all public attributes within the initialize_with block by calling attributes:

factory :user do
  transient do
    comments_count { 5 }
  end

  name "John Doe"

  initialize_with { new(**attributes) }
end

This will build a hash of all attributes to be passed to new. It won't include transient attributes, but everything else defined in the factory will be passed (associations, evaluated sequences, etc.)

You can define initialize_with for all factories by including it in the FactoryBot.define block:

FactoryBot.define do
  initialize_with { new("Awesome first argument") }
end

When using initialize_with, attributes accessed from within the initialize_with block are assigned only in the constructor; this equates to roughly the following code:

FactoryBot.define do
  factory :user do
    initialize_with { new(name) }

    name { 'value' }
  end
end

build(:user)
# runs
User.new('value')

This prevents duplicate assignment; in versions of factory_bot before 4.0, it would run this:

FactoryBot.define do
  factory :user do
    initialize_with { new(name) }

    name { 'value' }
  end
end

build(:user)
# runs
user = User.new('value')
user.name = 'value'

Custom Strategies

There are times where you may want to extend behavior of factory_bot by adding a custom build strategy.

Strategies define two methods: association and result. association receives a FactoryBot::FactoryRunner instance, upon which you can call run, overriding the strategy if you want. The second method, result, receives a FactoryBot::Evaluation instance. It provides a way to trigger callbacks (with notify), object or hash (to get the result instance or a hash based on the attributes defined in the factory), and create, which executes the to_create callback defined on the factory.

To understand how factory_bot uses strategies internally, it's probably easiest to view the source for each of the four default strategies.

Here's an example of composing a strategy using FactoryBot::Strategy::Create to build a JSON representation of your model.

class JsonStrategy
  def initialize
    @strategy = FactoryBot.strategy_by_name(:create).new
  end

  delegate :association, to: :@strategy

  def result(evaluation)
    @strategy.result(evaluation).to_json
  end

  def to_sym
    :json
  end
end

For factory_bot to recognize the new strategy, you can register it:

FactoryBot.register_strategy(:json, JsonStrategy)

This allows you to call

FactoryBot.json(:user)

Finally, you can override factory_bot's own strategies if you'd like by registering a new object in place of the strategies.

Custom Callbacks

Custom callbacks can be defined if you're using custom strategies:

class JsonStrategy
  def initialize
    @strategy = FactoryBot.strategy_by_name(:create).new
  end

  delegate :association, to: :@strategy

  def result(evaluation)
    result = @strategy.result(evaluation)
    evaluation.notify(:before_json, result)

    result.to_json.tap do |json|
      evaluation.notify(:after_json, json)
      evaluation.notify(:make_json_awesome, json)
    end
  end

  def to_sym
    :json
  end
end

FactoryBot.register_strategy(:json, JsonStrategy)

FactoryBot.define do
  factory :user do
    before(:json)                { |user| do_something_to(user) }
    after(:json)                 { |user_json| do_something_to(user_json) }
    callback(:make_json_awesome) { |user_json| do_something_to(user_json) }
  end
end

Custom Methods to Persist Objects

By default, creating a record will call save! on the instance; since this may not always be ideal, you can override that behavior by defining to_create on the factory:

factory :different_orm_model do
  to_create { |instance| instance.persist! }
end

To disable the persistence method altogether on create, you can skip_create for that factory:

factory :user_without_database do
  skip_create
end

To override to_create for all factories, define it within the FactoryBot.define block:

FactoryBot.define do
  to_create { |instance| instance.persist! }


  factory :user do
    name { "John Doe" }
  end
end

ActiveSupport Instrumentation

In order to track what factories are created (and with what build strategy), ActiveSupport::Notifications are included to provide a way to subscribe to factories being compiled and run. One example would be to track factories based on a threshold of execution time.

ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload|
  execution_time_in_seconds = finish - start

  if execution_time_in_seconds >= 0.5
    $stderr.puts "Slow factory: #{payload[:name]} using strategy #{payload[:strategy]}"
  end
end

Another example would be tracking all factories and how they're used throughout your test suite. If you're using RSpec, it's as simple as adding a before(:suite) and after(:suite):

factory_bot_results = {}
config.before(:suite) do
  ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |name, start, finish, id, payload|
    factory_name = payload[:name]
    strategy_name = payload[:strategy]
    factory_bot_results[factory_name] ||= {}
    factory_bot_results[factory_name][strategy_name] ||= 0
    factory_bot_results[factory_name][strategy_name] += 1
  end
end

config.after(:suite) do
  puts factory_bot_results
end

Another example could involve tracking the attributes and traits that factories are compiled with. If you're using RSpec, you could add before(:suite) and after(:suite) blocks that subscribe to factory_bot.compile_factory notifications:

factory_bot_results = {}
config.before(:suite) do
  ActiveSupport::Notifications.subscribe("factory_bot.compile_factory") do |name, start, finish, id, payload|
    factory_name = payload[:name]
    factory_class = payload[:class]
    attributes = payload[:attributes]
    traits = payload[:traits]
    factory_bot_results[factory_class] ||= {}
    factory_bot_results[factory_class][factory_name] = {
      attributes: attributes.map(&:name)
      traits: traits.map(&:name)
    }
  end
end

config.after(:suite) do
  puts factory_bot_results
end

has_many associations

There are a few ways to generate data for a has_many relationship. The simplest approach is to write a helper method in plain Ruby to tie together the different records:

FactoryBot.define do
  factory :post do
    title { "Through the Looking Glass" }
    user
  end

  factory :user do
    name { "Rachel Sanchez" }
  end
end

def user_with_posts(posts_count: 5)
  FactoryBot.create(:user) do |user|
    FactoryBot.create_list(:post, posts_count, user: user)
  end
end

create(:user).posts.length # 0
user_with_posts.posts.length # 5
user_with_posts(posts_count: 15).posts.length # 15

If you prefer to keep the object creation fully within factory_bot, you can build the posts in an after(:create) callback.

FactoryBot.define do
  factory :post do
    title { "Through the Looking Glass" }
    user
  end

  factory :user do
    name { "John Doe" }

    # user_with_posts will create post data after the user has been created
    factory :user_with_posts do
      # posts_count is declared as a transient attribute available in the
      # callback via the context
      transient do
        posts_count { 5 }
      end

      # the after(:create) yields two values; the user instance itself and the
      # context, which stores all values from the factory, including transient
      # attributes; `create_list`'s second argument is the number of records
      # to create and we make sure the user is associated properly to the post
      after(:create) do |user, context|
        create_list(:post, context.posts_count, user: user)

        # You may need to reload the record here, depending on your application
        user.reload
      end
    end
  end
end

create(:user).posts.length # 0
create(:user_with_posts).posts.length # 5
create(:user_with_posts, posts_count: 15).posts.length # 15

Or, for a solution that works with build, build_stubbed, and create (although it doesn't work well with attributes_for), you can use inline associations:

FactoryBot.define do
  factory :post do
    title { "Through the Looking Glass" }
    user
  end

  factory :user do
    name { "Taylor Kim" }

    factory :user_with_posts do
      posts { [association(:post)] }
    end
  end
end

create(:user).posts.length # 0
create(:user_with_posts).posts.length # 1
build(:user_with_posts).posts.length # 1
build_stubbed(:user_with_posts).posts.length # 1

For more flexibility you can combine this with the posts_count transient attribute from the callback example:

FactoryBot.define do
  factory :post do
    title { "Through the Looking Glass" }
    user
  end

  factory :user do
    name { "Adiza Kumato" }

    factory :user_with_posts do
      transient do
        posts_count { 5 }
      end

      posts do
        Array.new(posts_count) { association(:post) }
      end
    end
  end
end

create(:user_with_posts).posts.length # 5
create(:user_with_posts, posts_count: 15).posts.length # 15
build(:user_with_posts, posts_count: 15).posts.length # 15
build_stubbed(:user_with_posts, posts_count: 15).posts.length # 15

has_and_belongs_to_many associations

Generating data for a has_and_belongs_to_many relationship is very similar to the above has_many relationship, with a small change: you need to pass an array of objects to the model's pluralized attribute name rather than a single object to the singular version of the attribute name.

def profile_with_languages(languages_count: 2)
  FactoryBot.create(:profile) do |profile|
    FactoryBot.create_list(:language, languages_count, profiles: [profile])
  end
end

Or with the callback approach:

factory :profile_with_languages do
  transient do
    languages_count { 2 }
  end

  after(:create) do |profile, context|
    create_list(:language, context.languages_count, profiles: [profile])
    profile.reload
  end
end

Or the inline association approach (note the use of the instance method here to refer to the profile being built):

factory :profile_with_languages do
  transient do
    languages_count { 2 }
  end

  languages do
    Array.new(languages_count) do
      association(:language, profiles: [instance])
    end
  end
end

Polymorphic associations

Polymorphic associations can be handled with traits:

FactoryBot.define do
  factory :video
  factory :photo

  factory :comment do
    for_photo # default to the :for_photo trait if none is specified

    trait :for_video do
      association :commentable, factory: :video
    end

    trait :for_photo do
      association :commentable, factory: :photo
    end
  end
end

This allows us to do:

create(:comment)
create(:comment, :for_video)
create(:comment, :for_photo)

Interconnected associations

There are limitless ways objects might be interconnected, and factory_bot may not always be suited to handle those relationships. In some cases it makes sense to use factory_bot to build each individual object, and then to write helper methods in plain Ruby to tie those objects together.

That said, some more complex, interconnected relationships can be built in factory_bot using inline associations with reference to the instance being built.

Let's say your models look like this, where an associated Student and Profile should both belong to the same School:

class Student < ApplicationRecord
  belongs_to :school
  has_one :profile
end

class Profile < ApplicationRecord
  belongs_to :school
  belongs_to :student
end

class School < ApplicationRecord
  has_many :students
  has_many :profiles
end

We can ensure the student and profile are connected to each other and to the same school with a factory like this:

FactoryBot.define do
  factory :student do
    school
    profile { association :profile, student: instance, school: school }
  end

  factory :profile do
    school
    student { association :student, profile: instance, school: school }
  end

  factory :school
end

Note that this approach works with build, build_stubbed, and create, but the associations will return nil when using attributes_for.

Also, note that if you assign any attributes inside a custom initialize_with (e.g. initialize_with { new(**attributes) }), those attributes should not refer to instance, since it will be nil.