Factory Bot step definitions for Cucumber

Did you know… Factory Bot includes some steps for your integration testing pleasure? They are currently available but remain relatively unknown.

Read the source at features/step_definitions/factory_bot_steps.rb. They make Direct Model Access a little easier from your Cucumber features.

Example usage

Define your factories normally in test/factories.rb or spec/factories.rb:

Factory.define :user do |user|
  user.email                 { Factory.next(:email) }
  user.password              { "password" }
  user.password_confirmation { "password" }

Factory.define :author, :parent => :user do |author|
  author.after(:create) { |a| Factory(:article, :author => a) }

Factory.define :recruiter, :parent => :user do |recruiter|
  recruiter.is_recruiter { true }

Make sure Factory Bot is available in your config/environments/cucumber.rb:

config.gem 'factory_bot', :version => '>= 1.2.3'

Require Factory Bot’s step definitions in features/support/env.rb:

require 'factory_bot/step_definitions'

Then, write Cucumber features using the simple “create record” step:

Given a user exists

… or the “create record & set one attribute” step:

Given an author exists with an email of "author@example.com"

… or the “create record & set multiple attributes” step:

Given the following recruiter exists:
  | email            | phone number | employer name |
  | bill@example.com | 1234567890   | thoughtbot    |

Avoid boilerplate

These steps will be available for all your factories, so stop writing boilerplate steps and shake what Factory Bot gave you.


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