如何解决factory_girl错误的参数个数错误

时间:2011-07-26 23:19:31

标签: ruby factory-bot

#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会导致此错误
  
    

引发ArgumentError:            错误的参数数量(0表示2)

  

3 个答案:

答案 0 :(得分:20)

现在确实如此。在4.1版上测试:

FactoryGirl.define do

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

参考:documentation

答案 1 :(得分:10)

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

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

所以你需要做其中任何一个(仅在你的测试设置代码中):

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

答案 2 :(得分:0)

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

FactoryBot.lint verbose: true

有关详细信息,请参见the documentation