ypicard
ypicard

Reputation: 3703

How to override class initialize method and use FactoryBot?

I'm using FactoryBot with Rspec on rails.

I have a SpecificKeyword ruby class where I extend the inittialize method:

def initialize(args)
   super(args)
   # Init regexp field immediatly when creating keyword
   self.regexp = make_regexp(args[:specificity])
end

In my Rspec tests, i try to call this: @kw_ex = create(:specific_keyword, name: 'Test Keyword').

But I get this stack trace:

 ArgumentError:
        wrong number of arguments (0 for 1)
      # ./app/models/specific_keyword.rb:19:in `initialize'

It looks like when instantiating a SpecificKeyword with FactoryBot, no args are passed to the init method. Is this a desired behavior, and if so, how am I supposed to proceed to keep using FactoryBot for my tests? It does work when I just do SpecificKeyword.new(name:'Test').

If I do not override the initialize method, it does work.

Upvotes: 6

Views: 5421

Answers (1)

nattfodd
nattfodd

Reputation: 1900

FactoryBot supports custom initializers looks like exactly your case:

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

Upvotes: 10

Related Questions