JoaoHornburg JoaoHornburg - 1 year ago 84
Ruby Question

How to pass parameters through the associations chain in FactoryGirl

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

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
all the way through the associations to the Account factory. Is there a way to do it so?

Answer Source

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
    posts_manager {, :user => user) }

  factory :posts_manager do
    ignore do
      user nil
    account {, :user => user) }

  factory :account do
    user { user }


FactoryGirl.create(:post, :user => current_user)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download