FactoryBot 2.1.0 Brings the Heat

Josh Clayton

Factory Bot has seen a handful of changes over the past six weeks since we released 2.0.0. Some of the highlights:

Simple association syntax

factory :user do
  name "John doe"
end

factory :post do
  author :factory => :user
end

Traits

trait :male do
  gender "Male"
end

trait :admin do
  admin true
end

factory :user do
  factory :male_user,       :traits => [:male]
  factory :admin,           :traits => [:admin]
  factory :male_admin_user, :traits => [:male, :admin]
end

Transient attributes

factory :user do
  rockstar(true).ignore
  name { "Johnny#{" Rockstar" if rockstar}" }
end

> FactoryBot.create(:user).name                     # "Johnny Rockstar"
> FactoryBot.create(:user, :rockstar => false).name # "Johnny"

Change associations to build instead of create

factory :profile do
  sequence(:username) {|n| "user-#{n}" }
end

factory :user do
  profile :method => :build
end

Factory modification

FactoryBot.define do
  factory :user do
    name "John Doe"
    sequence(:email) {|n| "user-#{n}@example.com" }
  end
end

FactoryBot.modify do
  factory :user do
    email { "#{name.downcase.underscore}@example.com" }
  end
end

Factory reloading (handy in a console)

FactoryBot.reload # reloads all factories, sequences, and traits

Apart from these features, we’ve ensured that Factory Bot processes different attributes (static attributes, dynamic attributes) in a reasonable order, verified it works on Rails 3.1.0, upgraded the test suite to use Mocha + Bourne instead of RR, and a handful of other handy bug fixes.

Grab Factory Bot 2.1.0 and make testing easier!


Disclaimer:

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