How to resolve factory_girl wrong number of arguments error
Asked Answered
R

3

10
#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 the @room

ArgumentError: wrong number of arguments (0 for 2)

Risley answered 26/7, 2011 at 23:19 Comment(0)
M
10

FactoryGirl does not currently support initializers with arguments. So it fails when it's trying to do Room.new when you run build.

One simple workaround for this might be to monkey-patch your classes in your test setup to get around this issue. It's not the ideal solution, but you'll be able to run your tests.

So you'd need to do either one of these (just in your test setup 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

Marismarisa answered 27/7, 2011 at 0:18 Comment(1)
Thank you, what an unexpected error, I was thinking its me :-)Machination
O
23

Now it does. Tested on version 4.1:

FactoryGirl.define do

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

end

Reference: documentation

Overelaborate answered 18/10, 2012 at 18:17 Comment(0)
M
10

FactoryGirl does not currently support initializers with arguments. So it fails when it's trying to do Room.new when you run build.

One simple workaround for this might be to monkey-patch your classes in your test setup to get around this issue. It's not the ideal solution, but you'll be able to run your tests.

So you'd need to do either one of these (just in your test setup 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

Marismarisa answered 27/7, 2011 at 0:18 Comment(1)
Thank you, what an unexpected error, I was thinking its me :-)Machination
L
1

What was useful for me, was enabling debug output for FactoryBot linting:

FactoryBot.lint verbose: true

see the documentation for the details

Lixivium answered 27/8, 2019 at 9:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.