How to pass parameters through the associations chain in FactoryGirl

JoaoHornburg picture JoaoHornburg · Jul 10, 2013 · Viewed 9.9k times · Source

By default, FactoryGirl calls the factories of associations to create them. I can pass a association for a factory as a parameter. But how can I passa an object which should be used deep in the associations chain?

For example:

I have a Post, which has a PostsManager, which has an Account, which belongs to the current_user.

When I do a Factory(:post) it creates an PostsManager, which creates an Account, which doesn't belongs to the (stubed) current_user.

So, in specs that use the Post factory I have to do:

account = Factory(:account, user: current_user)
post_manager = Factory(:post_manager, account: account)
post = Factory(:post, post_manager: post_manager)

What I would like to do is call the factory with Factory(:post, user: current_user), and then pass current_user all the way through the associations to the Account factory. Is there a way to do it so?

Answer

Jacob Brown picture Jacob Brown · Jul 10, 2013

Not sure what version of FactoryGirl you are using, but if you are on any recent version (2.6+) you can use Transient Attributes (read more on their "Getting Started" page). You could do something like this:

FactoryGirl.define do

  factory :post do
    ignore do
      user nil
    end
    posts_manager { FactoryGirl.build(:posts_manager, :user => user) }
  end

  factory :posts_manager do
    ignore do
      user nil
    end
    account { FactoryGirl.build(:account, :user => user) }
  end

  factory :account do
    user { user }
  end

end

FactoryGirl.create(:post, :user => current_user)