ngcable
ngcable

Reputation: 33

factory_bot does not support initialize_with keyword arguments

Given the following class:

class URL
  attr_reader :description
  attr_reader :url

  def initialize(description:, url:)
  end
end

and the following factory bot definition:

FactoryBot.define do
  factory :url, class: URL do
    description { 'test_description' }
    url { 'test_url' }
   
    initialize_with { new(description: description, url: url) }
  end
end

It raises the exception:

ArgumentError: wrong number of arguments (given 1, expected 0; required keywords: description, url)

Also tried: initialize_with { new(**attributes) } with the same outcome.

Running with: factory_bot 6.2.1 and ruby 3.0.4

Any insights on why this happening? Or it is something unsupported?

Upvotes: 0

Views: 365

Answers (1)

jansha
jansha

Reputation: 171

In this class initialize method, where we have assigned the instance variables?,

As you are using keyword argument for initialize method of the URL class, so the parameters need to be defined seperately.

like this:

class URL
  attr_reader :description
  attr_reader :url

  def initialize(description:, url:)
    @description = description
    @url = url
  end
end

Upvotes: 0

Related Questions