thoughtbot/factory_girl — Issue #231: Non expected created association
Author: marioizquierdo
Created: 2011-11-08 20:37:59+00:00
State: open

Given uses and posts, where Post belongs_to users:

FactoryGirl.define do
factory :users
sequence :user_id
end

factory :posts
association :owner, :factory => :user
end
end

Then, when I create a new post:

FactoryGirl.create :post

It will create a user first, and then the post assigning the owner_id to the user.id.

That's fine, but if I want to use a existing user and do not create a new one:

existing_user = User.find_by_user_id 1234
FactoryGirl.create :post, :owner => existing_user

This will create a new user, then build the post, then assign the created user.id, then override owner_id with the id of existing_user, and finally save the post.

In the end, we have a post with the right owner_id, but an extra User object was created.

This is odd if the association needs some validations, and it will make tests more slow by creating unneeded records.