How to solve the wrong number of arguments factory_girl

#rspec test code @room = FactoryGirl.build(:room) #factory definition factory :room do length {10} width {20} end #code implementation class Room attr_accessor :length, :width def initialize(length,width) @length = length @width = width end end 

Running rspec results in this error when trying to build @room

ArgumentError: invalid number of arguments (0 to 2)

+10
ruby factory-bot
source share
3 answers

FactoryGirl does not currently support initializers with arguments. Therefore, when you start build it tries to execute Room.new .

One of the easiest ways to solve this problem is to deactivate your classes in a test setup to work around this problem. This is not an ideal solution, but you can run tests.

Thus, you will need to do one of them (only in your test installation code):

 class Room def initialize(length = nil, width = nil) ... end end 

or

 class Room def initialize ... end end 

The issue is discussed here:
https://github.com/thoughtbot/factory_girl/issues/42

... and here:
https://github.com/thoughtbot/factory_girl/issues/19

+10
source share

Now it is. Tested on version 4.1:

 FactoryGirl.define do factory :room do length 10 width 20 initialize_with { new(length, width) } end 

end

Link: documentation

+21
source share

It was useful for me to enable debugging output for FactoryBot links:

 FactoryBot.lint verbose: true 

See the documentation for details.

0
source share

All Articles