Factories

Learn about the uses of factories and how to install factories.

Factories

Generically, the factory pattern refers to a class or module in the application whose sole purpose is to safely and correctly create other objects in the application. Outside of tests, factories are frequently used to encapsulate complex object-creation logic. Inside of Rails tests, factories are used to provide templates for creating valid objects.

Uses of factories

Rather than specifying all the test data exactly, the factory tool provides a blueprint for creating a sample instance of the model. When we need data for a specific test, we call a factory method, which gives us an object based on the blueprint. We can override the blueprint to identify any specific attribute values required to make the test work out. Calling the factory method is simple enough to make it feasible to set up a useful amount of data in each test.

The factory_bot tool

The most common factory tools used for Rails testing are factory_bot and its Rails library, factory_bot_rails. Until quite recently, this gem was called factory_girl, so we’ll likely see many references to it under that name.

Let’s talk first about how to set up and use factory_bot, and once we have the basics down, we’ll discuss how to use it effectively.

Installing factory_bot

To install factory_bot in a Rails project, include the following in the Gemfile in the development and test group:

gem 'factory_bot_rails'

Factory files directory

In a Rails project, factory files are automatically loaded if they are in spec/factories.rb or spec/factories/*.rb. In Minitest-land, that would be test/factories.rb or test/factories/*.rb. Factories defined in any other place need to be explicitly required in the program.

Factories setup

There’s one optional configuration, which is to place the following line inside the configuration definition in spec/rails_helper.rb or some other file that is loaded as part of the RSpec setup:

Get hands-on with 1200+ tech skills courses.