如何解决factory_girl参数数量错误错误

发布于 2024-11-26 15:21:14 字数 428 浏览 0 评论 0原文

#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)

#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

Running rspec results in this error when trying to build the @room

ArgumentError:
wrong number of arguments (0 for 2)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

徒留西风 2024-12-03 15:21:14

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

FactoryGirl.define do

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

结束

参考:文档

Now it does. Tested on version 4.1:

FactoryGirl.define do

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

end

Reference: documentation

故人如初 2024-12-03 15:21:14

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

FactoryGirl does not currently support initializers with arguments. So it fails when it's trying to do Room.new when you run build.

One simple workaround for this might be to monkey-patch your classes in your test setup to get around this issue. It's not the ideal solution, but you'll be able to run your tests.

So you'd need to do either one of these (just in your test setup code):

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

or

class Room
  def initialize
    ...
  end
end

The issue is discussed here:
https://github.com/thoughtbot/factory_girl/issues/42

...and here:
https://github.com/thoughtbot/factory_girl/issues/19

戏蝶舞 2024-12-03 15:21:14

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

FactoryBot.lint verbose: true

请参阅 文档了解详细信息

What was useful for me, was enabling debug output for FactoryBot linting:

FactoryBot.lint verbose: true

see the documentation for the details

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文