2011-09-20 102 views
7

我正在使用Ruby on Rails 3.0.9,RSpec-rails 2和FactoryGirl。我试图说明一个工厂协会模型,但我有麻烦。FactoryGirl关联模型麻烦:“SystemStackError:堆栈级别太深”

我有一个factories/user.rb文件类似如下:

FactoryGirl.define do 
    factory :user, :class => User do 
    attribute_1 
    attribute_2 
    ... 

    association :account, :factory => :users_account, :method => :build, :email => '[email protected]' 
    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 

上面的示例将按预期在我的规范文件,但如果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 

我怎样才能解决这个问题,所以从两侧\工厂访问关联模型(也就是,在我的规范文件,我想用回报率协会模型方法如user.accountaccount.user

P.S .:我读了Factory Girl and has_one的问题,我的情况与链接问题中解释的情况非常接近。也就是说,我也有一个has_one关联(在UserUsers::Account类之间)。

+0

只是好奇,你有一个'用户',然后你有一个'用户::帐户',是否应该是复数或应该是'User :: Account'或错字? – nowk

+0

@kwon - 这不是一个错字。我有一个'Users :: Account'类。 – Backo

回答

14

根据the docs,你不能只将关联的双方放入工厂。你需要使用他们的回调后设置一个对象返回。

例如,在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 
相关问题