如何重写类的初始化方法并使用FactoryBot?

pic

我在Rspec上使用FactoryBot。

我有一个我在其中扩展方法SpecificKeyword ruby类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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章