27

默认情况下,FactoryGirl 调用关联工厂来创建它们。我可以将工厂的关联作为参数传递。但是我怎样才能传递一个应该在关联链深处使用的对象呢?

例如:

我有一个 Post,它有一个 PostsManager,它有一个 Account,它属于 current_user。

当我这样做时,Factory(:post)它会创建一个 PostsManager,它会创建一个不属于(存根)current_user 的帐户。

因此,在使用 Post 工厂的规范中,我必须这样做:

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

我想做的是用 调用工厂Factory(:post, user: current_user),然后current_user一直通过关联传递给 Account 工厂。有没有办法做到这一点?

4

1 回答 1

25

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)
于 2013-07-10T18:57:18.290 回答