Skip to content

How factory_bot interacts with ActiveRecord

Leif Ringstad edited this page Nov 1, 2017 · 1 revision

When you invoke a factory, factory_bot uses your definitions to compile a list of attributes that should be assigned to that instance, as well as any associated factories. It saves associations first so that foreign keys will be properly set on dependent models. To create an instance, it calls new without any arguments, assigns each attribute (including associations), and then calls save!. factory_bot doesn’t do anything special to create ActiveRecord instances. It doesn’t interact with the database or extend ActiveRecord or your models in any way.

As an example, take these factory definitions:

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

  factory :user do
    email
  end

  factory :post do
    user
    title "Hello"
  end
end

If you call:

post = create(:post)

That’s roughly equivalent to writing the following:

user = User.new
user.email = "person-1@example.com"
user.save!
post = Post.new
post.title = "Hello"
post.user = user
post.save!

When it has a polymorphic association:

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

  factory :user do
    email
  end

  factory :post do
    association :author, factory: :user
    title "Hello"
  end
end

If you’re having trouble getting factory_bot to build an instance as expected, try building your model from rails console using the same attributes. If you can’t build an instance of your factory, neither can factory_bot. Please make sure to try out your models without using factory_bot before filing a factory_bot bug.