Short, Explicit Test Setups

Dan Croak

You probably know about this Factory Bot1 definition syntax:

FactoryBot.define do
  factory :user do
    name { 'Connie Customer' }
  end
end

But did you know about this Factory Bot invocation syntax?

setup do
  @user = create(:user)
end

Or:

setup do
  @user = build(:user)
end

Or:

setup do
  post :create, user: attributes_for(:user)
end

It’s in there.

Configuration for Test::Unit / Shoulda:

class ActiveSupport::TestCase
  include FactoryBot::Syntax::Methods
end

Configuration for RSpec:

RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end

Configuration for Cucumber:

World FactoryBot::Syntax::Methods

Project name history can be found here.


  1. Looking for FactoryGirl? The library was renamed in 2017.