【问题标题】:RSpec/FactoryGirl Stack level too deepRSpec/FactoryGirl 堆栈级别太深
【发布时间】:2014-04-22 23:40:27
【问题描述】:

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

所以我有 3 个模型:Foo、Bar 和 Lol

  • Foo has_many Bars
  • 哈哈 has_many 酒吧
  • 酒吧属于 Foo & Lol

这是给我错误的代码。

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

我正在努力让这个测试通过

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

【问题讨论】:

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


    【解决方案1】:

    您当前的工厂设置正在进行大量递归,导致Stack level too deep 错误。

    总之,当你拨打foo = FactoryGirl.create(:foo)

    工厂 :foo => create_list(:bar, 1, foo: foo) => 工厂 :bar => factory :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
    

    【讨论】:

    • 非常感谢!你的解释清楚而简洁。我唯一的遗憾是我只投了一票。
    • 所以我尝试将其实现到我的真实代码中,但没有按预期工作。我在这里提出了一个新问题:stackoverflow.com/questions/23237040/associations-not-loading如果你能帮助我解决这个问题,我将不胜感激!
    猜你喜欢
    • 2015-04-01
    • 2012-03-04
    • 2013-10-05
    • 2016-09-10
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2012-07-24
    相关资源
    最近更新 更多