I'm having trouble with what looks like a very simple problem.
So I have 3 models: Foo, Bar, and Lol
Here's the code that's giving me errors.
spec/factories/foos.rb
FactoryGirl.define do
factory :foo do
after(:create) do |foo|
create_list(:bar, 1, foo: foo)
end
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
after(:create) do |lol|
create_list(:bar, 1, lol: lol)
end
end
end
I'm trying to get this test to pass
spec/models/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
You have a lot of recursion going on with your current factories setup which is causing the Stack level too deep
error.
In short, when you call foo = FactoryGirl.create(:foo)
factory :foo => create_list(:bar, 1, foo: foo) => factory :bar => factory :foo => create_list(:bar, 1, foo: foo) ...... keeps looping
Same for lol
.
You would need to refactor your code. One possible solution is as below:
Change your factories as:
## 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
Update your example as below:
## 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.