Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 }

like image 716
B Seven Avatar asked Oct 18 '12 16:10

B Seven


1 Answers

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.

like image 152
Zach Kemp Avatar answered Nov 01 '22 05:11

Zach Kemp