How to pass parameters through the associations chain in FactoryGirl
Asked Answered
G

1

27

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?

Graphy answered 10/7, 2013 at 13:18 Comment(4)
Would you add code example.Ceramic
Read sscce.org please. Without more information we're not able to give you accurate answers.Hendiadys
He's asking if attributes can be passed down through associations if they don't exist on the original models. This can be done with transient attributes. I have an answer if you will re-open the question.Degenerate
made some changes. Hope you can understand it nowGraphy
D
27

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)
Degenerate answered 10/7, 2013 at 18:57 Comment(2)
I wish I had found this 2 years ago.Moreville
For recent versions of FactoryGirl, use transient instead of ignoreMireyamiriam

© 2022 - 2024 — McMap. All rights reserved.