如何覆盖 class 初始化方法并使用 FactoryBot?
How to override class initialize method and use FactoryBot?
我在 rails 上将 FactoryBot 与 Rspec 一起使用。
我有一个 SpecificKeyword ruby class 我在其中扩展了 inittialize
方法:
def initialize(args)
super(args)
# Init regexp field immediatly when creating keyword
self.regexp = make_regexp(args[:specificity])
end
在我的 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'
看起来在使用 FactoryBot 实例化 SpecificKeyword 时,没有将任何参数传递给 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
https://robots.thoughtbot.com/factory-girl-2-5-gets-custom-constructors
我在 rails 上将 FactoryBot 与 Rspec 一起使用。
我有一个 SpecificKeyword ruby class 我在其中扩展了 inittialize
方法:
def initialize(args)
super(args)
# Init regexp field immediatly when creating keyword
self.regexp = make_regexp(args[:specificity])
end
在我的 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'
看起来在使用 FactoryBot 实例化 SpecificKeyword 时,没有将任何参数传递给 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
https://robots.thoughtbot.com/factory-girl-2-5-gets-custom-constructors