New Factory Bot Definition Syntax

Dan Croak

factory_bot and factory_bot_rails release candidates were released this week thanks to Joe and Josh.

The big change is some great-looking new syntax. Check it out:

Old:

Factory.sequence :email do |n|
  "email#{n}@example.com"
end

Factory.define :user do |factory|
  factory.name  { 'Ron Burgundy' }
  factory.email { Factory.next(:email) }
end

Factory.define :admin, parent: :user do |factory|
  factory.admin { true }
end

Factory.define :dog do |factory|
  factory.name { 'Baxter' }
  factory.association(:owner, factory: :user)
end

New:

FactoryBot.define do
  sequence :email do |n|
    "email#{n}@example.com"
  end

  factory :user, aliases: [:owner] do
    name { 'Ron Burgundy' }
    email

    factory :admin do
      admin { true }
    end
  end

  factory :dog do
    name { 'Baxter' }
    owner
  end
end

It reminds me of the difference between Rails 2.x routes and Rails 3.x routes.

Read the factory_bot book, then try it in your app:

gem 'factory_bot_rails', '1.1.rc1'

Disclaimer:

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

About thoughtbot

We've been helping engineering teams deliver exceptional products for over 20 years. Our designers, developers, and product managers work closely with teams to solve your toughest software challenges through collaborative design and development. Learn more about us.