Skip to content

How factory_girl interacts with ActiveRecord

joshuaclayton edited this page Mar 23, 2012 · 6 revisions

When you invoke a factory, factory_girl 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_girl 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:

FactoryGirl.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:

FactoryGirl.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_girl 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_girl. Please make sure to try out your models without using factory_girl before filing a factory_girl bug.

Clone this wiki locally