How to use FactoryGirl with a model that takes a hash in initialize method?
Asked Answered
A

1

11

Seems simple, but haven't been able to figure out how to get this to work.

In model.rb:

def Model
  attr_accessor :width,
                :height

  def initialize params
    @width = params[:width]
    @height = params[:height]
    ...

In factory file models.rb:

FactoryGirl.define do
  factory :model do
    height 5
    width 7
  end
end

Setting the attributes in the factory method throws an error wrong number of arguments (0 for 1)

Working in Ruby 1.9.3 without Rails, using Factory.build. FactoryGirl 4.1.

EDIT: More info:

Using RSpec: let(:model) { FactoryGirl.build :model }

Addlebrained answered 18/10, 2012 at 16:11 Comment(1)
This looks like a standard FactoryGirl definition. How are you calling Factory.build? Could you post the full contents of your factory definition, including any after_build or after_create hooks?Teapot
M
31

This should work with your class:

FactoryGirl.define do

  factory :model do
    skip_create

    width 5
    height 9

    initialize_with { new(attributes) }
  end
end

-skip_create bypasses the default save! action normally called on new objects.

-The attributes method generates a hash you can pass to new using initialize_with.

Maisiemaison answered 18/10, 2012 at 16:25 Comment(6)
This passes in an empty hash. initialize_with {{ height: 5, width: 6 }} passes in the appropriate hash, but the factory returns the hash instead of the model object.Addlebrained
You're right; there shouldn't be an ignore block. Removing it now.Maisiemaison
How did you ever find this out?Addlebrained
Would you please add the link to the docs? (preferably to the answer)Stethoscope
@TylerCollier github.com/thoughtbot/factory_girl/blob/master/… under Custom ConstructionTracheotomy
github.com/thoughtbot/factory_bot/blob/master/…Cello

© 2022 - 2024 — McMap. All rights reserved.