FactoryGirl关联模型故障:“SystemStackError:堆栈级别太深”
我正在使用Ruby on Rails 3.0.9,RSpec-rails 2和FactoryGirl。 我试图陈述一个工厂协会模型,但我遇到了麻烦。
我有一个factories/user.rb
文件,如下所示:
FactoryGirl.define do factory :user, :class => User do attribute_1 attribute_2 ... association :account, :factory => :users_account, :method => :build, :email => 'foo@bar.com' end end
和一个factories/users/account.rb
文件如下:
FactoryGirl.define do factory :users_account, :class => Users::Account do sequence(:email) {|n| "foo#{n}@bar.com" } ... end end
上面的示例在我的spec文件中按预期工作,但是如果在factory :users_account
语句我添加了association :user
代码所以要有
FactoryGirl.define do factory :users_account, :class => Users::Account do sequence(:email) {|n| "foo#{n}@bar.com" } ... association :user end end
我收到以下错误:
Failure/Error: Unable to find matching line from backtrace SystemStackError: stack level too deep
如何解决这个问题,以便从双方\工厂访问相关模型 (也就是说,在我的spec文件中,我想使用像user.account
和account.user
这样的RoR关联模型方法) ?
PS:我读过工厂女孩并且有一个问题,我的案子非常接近于相关问题中解释的案例。 也就是说,我也有一个has_one
关联(在User
和Users::Account
类之间)。
根据文档 ,你不能只把协会的双方都放进工厂。 您需要使用它们的after回调来设置要返回的对象。
例如,在factories/users/account.rb
文件中,您可以输入类似的内容
after(:build) do |user_account, evaluator| user_account.user = FactoryGirl.build(:user, :account=>user_account) end
对于has_many关联,您需要使用他们的* _list函数。
after(:build) do |user_account, evaluator| user_account.users = FactoryGirl.build_list(:user, 5, :account=>user_account) end
注意:我认为文档中的示例有点误导,它没有为对象分配任何内容。 我相信它应该是(注意作业)。
# the after(:create) yields two values; the user instance itself and the # evaluator, which stores all values from the factory, including ignored # attributes; `create_list`'s second argument is the number of records # to create and we make sure the user is associated properly to the post after(:create) do |user, evaluator| user.posts = FactoryGirl.create_list(:post, evaluator.posts_count, user: user) end