Ruby On Rails: Factory Girl : How it interacts with ActiveRecord

Many of us wonder how the FactoryGirl create ActiveRecord objects and how it deals with the associations we set in the Models. Actually, it deals in straight forward way. You set association in factory definition like that you already set in the models and every thing is done by FactoryGirl.
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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s