Skip to content

Instantly share code, notes, and snippets.

@brianjbayer
Last active March 30, 2024 02:12
Show Gist options
  • Save brianjbayer/301b78a60a9d3a74a375d20fb6dfb744 to your computer and use it in GitHub Desktop.
Save brianjbayer/301b78a60a9d3a74a375d20fb6dfb744 to your computer and use it in GitHub Desktop.
Add the testing utility FactoryBot to your Rails project

Add and Configure FactoryBot To Your Rails RSpec Project

This guides you through adding the test data fixture utility factory_bot to your Ruby on Rails RSpec project.

To install factory_bot you will need to...

  1. Add the factory_bot_rails gem to your Rails RSpec project
  2. Configure factory_bot_rails to be used by RSpec Rails

🙇 📖 I originally learned this from these posts...


Add factory_bot_rails Gem to Your Rails RSpec Project

You need to add the factory_bot_rails gem to your Gemfile but really only need it for development and test.

  1. Edit your Gemfile and add gem 'factory_bot_rails' to just :development, :test group, for example...

    group :development, :test do
      # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
      gem "debug", platforms: %i[ mri windows ]
    
      # Add RSpec and test utilities and tools
      gem 'factory_bot_rails'
      gem 'rspec-rails'
    end
  2. Run bundle install to install the factory_bot_rails gem

    bundle install
    

    ☁️ If you are doing container-native development, be sure to run your bundle commands in the container environment


Configure factory_bot_rails To Be Used By RSpec Rails

You need to configure RSpec Rails to use factory_bot fixtures and methods in its specs.

You can add the factory_bot configuration directly to your rails_helper file, but you may find it cleaner to create a separate file and include it.

  1. Create a new spec/support/config/ directory if you do not already have one

    mkdir -p spec/support/config
  2. Create a new spec/support/config/factory_bot.rb file

    touch spec/support/config/factory_bot.rb
  3. Edit your spec/support/config/factory_bot.rb file to have the following...

    # frozen_string_literal: true
    
    # Add Factory Bot Methods to spec DSL
    RSpec.configure do |config|
     config.include FactoryBot::Syntax::Methods
    end
  4. Save your edited spec/support/config/factory_bot.rb file

  5. Edit your spec/rails_helper.rb file and add require 'support/config/factory_bot', for example...

    # Add additional requires below this line. Rails is not loaded until this point!
    require 'support/config/factory_bot'
  6. Save your edited spec/rails_helper.rb file

🏃 You should now be able to use the factory_bot methods to create your factory_bot test data.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment