Setup Factory Bot in Rails

Pinterest LinkedIn Tumblr

Factory Bot is a library for setting up test data objects in Ruby. Today we will be setting up Factory Bot in Rails which uses RSpec for testing. If you are using a different test suite, you can view all supported configurations here.

To setup Factory Bot in Rails, we should follow the steps given below:

  1. Add factory_bot_rails to your Gemfile in :development, :test group
      group :development, :test do
        gem 'factory_bot_rails'
  2. Install gem with bundle install
  3. Create a file spec/support/factory_bot.rb and add the following configuration inside
      RSpec.configure do |config|
        config.include FactoryBot::Syntax::Methods
  4. Uncomment the following line from rails_helper.rb so all files inside spec/support are loaded automatically by rspec
      # Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
      Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
  5. Check factory bot rails version inside Gemfile.lock and update the gem with that version in Gemfile. It was 6.1.0 while writing this tutorial, yours may be different depending on the latest gem version.
      group :development, :test do
        gem 'factory_bot_rails', '~> 6.1.0'
  6. Run bundle install (Optional, since nothing will change inside Gemfile.lock)
  7. Add factories folder inside spec folder if it doesn’t already exist. You can then create factories inside spec/factories folder.
  8. Assuming you have a model User, you can create factories/users.rb
  9. If attributes in users table are first_name, last_name, email, mobile_number. Your users factory will look something like this:
      FactoryBot.define do
        factory :user do
          first_name { 'John' }
          last_name  { 'Doe' }
          email { john@email_provider.com }
          mobile_number { 7860945310 }
  10. You can use the user factory inside your user_specs like this
        require 'rails_helper'
        RSpec.describe User, type: :model do
          let(:user) { build(:user) }
  11. You can view various use cases in the official documentation for using factories in your tests.


Factory Bot helps in reusing the same code in multiple test examples, this way you will have to write less code, and as they say “Less code is always better”.

Thank you for reading. Happy coding!


Image Credits: manfredsteger from Pixabay

Avatar photo

Freelancing Software Developer | Ruby on Rails, Reactjs, React Native, Gatsby, Saas, Bootstrap | Traveller | Spiritual Practitioner

Write A Comment