ypi*_*ard 3 rspec ruby-on-rails factory-bot
我在 Rails 上使用 FactoryBot 和 Rspec。
我有一个SpecificKeyword ruby 类,我在其中扩展了该inittialize方法:
def initialize(args)
super(args)
# Init regexp field immediatly when creating keyword
self.regexp = make_regexp(args[:specificity])
end
Run Code Online (Sandbox Code Playgroud)
在我的测试中Rspec的,我尝试调用此:
@kw_ex = create(:specific_keyword, name: 'Test Keyword')。
但我得到了这个堆栈跟踪:
ArgumentError:
wrong number of arguments (0 for 1)
# ./app/models/specific_keyword.rb:19:in `initialize'
Run Code Online (Sandbox Code Playgroud)
看起来当使用 FactoryBot 实例化一个特定关键字时,没有参数传递给 init 方法。这是一种理想的行为,如果是,我应该如何继续使用 FactoryBot 进行测试?当我这样做时它确实有效SpecificKeyword.new(name:'Test')。
如果我不覆盖该initialize方法,它确实有效。
FactoryBot 支持自定义初始值设定项与您的情况完全一样:
FactoryBot.define do
factory :specific_keyword do
transient do
name { 'some default' }
end
initialize_with { new(attributes.merge(name: name)) }
end
end
Run Code Online (Sandbox Code Playgroud)
https://robots.thoughtbot.com/factory-girl-2-5-gets-custom-constructors
| 归档时间: |
|
| 查看次数: |
2137 次 |
| 最近记录: |