Factory Bot 2.5 Gets Custom Constructors

Josh Clayton

Today marks a big day in the life of Factory Bot; you can now override the constructor for factories! This is great news for people who’ve been upset that they can’t use Factory Bot with objects who have constructors with required arguments, as Factory Bot 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
  end

  # ...
end

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

    initialize_with { ReportGenerator.new(name, data) }
  end

  # ...
end

Note that I wrapped the name and data attributes in an ignore block. Factory Bot 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 Bot with your other objects today!


Disclaimer:

Looking for FactoryGirl? The library was renamed in 2017. Project name history can be found here.