Factory Girl 2.5 Gets Custom Constructors

Today marks a big day in the life of Factory Girl; you can now override the constructor for factories! This is great news for people who’ve been upset that they can’t use Factory Girl with objects who have constructors with required arguments, as Factory Girl would previously just call new without passing any arguments.

Here’s the syntax:

# app/models/report_generator.rb
class ReportGenerator
  def initialize(name, data)
    @name = name
    @data = data

  # ...

# spec/factories.rb
FactoryGirl.define do
  factory :report_generator do
    ignore do
      name "Generic Report"
      data { {:foo => "bar", :baz => "buzz"} }

    initialize_with { ReportGenerator.new(name, data) }

  # ...

Note that I wrapped the name and data attributes in an ignore block. Factory Girl doesn’t differentiate between attributes passed in the custom constructor and normal attributes to assign, so moving them to the ignore block ensures that I don’t instantiate the report generator and then attempt to assign name and data again.

Grab a copy of 2.5.0 and start using Factory Girl with your other objects today!