RSpec / FactoryGirl堆栈级别太深

时间:2014-04-22 23:40:27

标签: ruby-on-rails ruby rspec factory-bot

我遇到了一个非常简单的问题。

所以我有3个模特:Foo,Bar和Lol

  • Foo has_many Bars
  • Lol has_many Bars
  • Bar belongs_to Foo&洛尔

以下是给我错误的代码。

规格/工厂/ 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

1 个答案:

答案 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