我遇到了一个非常简单的问题。
所以我有3个模特:Foo,Bar和Lol
以下是给我错误的代码。
规格/工厂/ foos.rb
FactoryGirl.define do
factory :foo do
after(:create) do |foo|
create_list(:bar, 1, foo: foo)
end
end
end
规格/工厂/ bars.rb
FactoryGirl.define do
factory :bar do
foo
lol
end
end
规格/工厂/ lols.rb
FactoryGirl.define do
factory :lol do
after(:create) do |lol|
create_list(:bar, 1, lol: lol)
end
end
end
我试图让这个测试通过
规格/模型/ foo_spec.rb
require 'spec_helper'
describe Foo do
it "works" do
foo = FactoryGirl.create(:foo)
puts foo.bars
foo.bars.each {|bar| puts bar.lol}
foo.should_not be_nil
end
end
答案 0 :(得分:2)
您当前的工厂设置会导致Stack level too deep
错误导致很多递归。
简而言之,当您致电foo = FactoryGirl.create(:foo)
工厂:foo => create_list(:bar,1,foo:foo)=>工厂:bar => 工厂:foo => create_list(:bar,1,foo:foo)......保持循环
lol
相同。
您需要重构代码。 一种可能的解决方案如下:
将您的工厂更改为:
## spec/factories/foos.rb
FactoryGirl.define do
factory :foo do
end
end
## spec/factories/bars.rb
FactoryGirl.define do
factory :bar do
foo
lol
end
end
## spec/factories/lols.rb
FactoryGirl.define do
factory :lol do
end
end
更新您的示例,如下所示:
## spec/models/foo_spec.rb
require 'spec_helper'
describe Foo do
it "works" do
foo = FactoryGirl.create(:bar).foo
puts foo.bars
foo.bars.each {|bar| puts bar.lol}
foo.should_not be_nil
end
end