【问题标题】:How to resolve factory_girl wrong number of arguments error如何解决 factory_girl 错误数量的参数错误
【发布时间】:2011-07-26 23:19:31
【问题描述】:
#rspec test code
@room = FactoryGirl.build(:room)

#factory definition
factory :room do
  length {10}
  width {20}
end

#code implementation
class Room
  attr_accessor :length, :width

  def initialize(length,width)
     @length = length
     @width = width 
  end

end

在尝试构建 @room 时运行 rspec 会导致此错误

参数错误: 参数数量错误(0 代表 2)

【问题讨论】:

    标签: ruby factory-bot


    【解决方案1】:

    现在可以了。在 4.1 版上测试:

    FactoryGirl.define do
    
      factory :room do
        length 10
        width 20
        initialize_with { new(length, width) }
      end
    

    结束

    参考:documentation

    【讨论】:

      【解决方案2】:

      FactoryGirl 目前不支持带参数的初始化程序。因此,当您运行build 时,它尝试执行Room.new 时会失败。

      一个简单的解决方法可能是在测试设置中对类进行猴子补丁以解决此问题。这不是理想的解决方案,但您可以运行测试。

      因此,您需要执行以下任一操作(仅在您的测试设置代码中):

      class Room
         def initialize(length = nil, width = nil)
           ...
         end
      end
      

      class Room
        def initialize
          ...
        end
      end
      

      这里讨论这个问题:
      https://github.com/thoughtbot/factory_girl/issues/42

      ...这里:
      https://github.com/thoughtbot/factory_girl/issues/19

      【讨论】:

      • 谢谢,真是个意外的错误,我以为是我 :-)
      【解决方案3】:

      对我有用的是为 FactoryBot linting 启用调试输出:

      FactoryBot.lint verbose: true
      

      详情请见the documentation

      【讨论】:

        猜你喜欢
        • 2017-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多