DEV Community

Cover image for Set up RSpec, Shoulda matchers and FactoryBot on Rails 7
Ankit Pariyar
Ankit Pariyar

Posted on

Set up RSpec, Shoulda matchers and FactoryBot on Rails 7

Rspec

  • Add rspec-rails on development and test group of Gemfile

    group :development, :test do
      gem 'rspec-rails'
    end
    
    • Then install it with command bundle install
  • Run command rails generate rspec:install for generating boilerplate config files. you can see following outputs:

    create  .rspec
    create  spec
    create  spec/spec_helper.rb
    create  spec/rails_helper.rb
    
  • Verify RSpec is correctly installed and configured by running bundle exec rspec you should see following outputs:

    No examples found.
    Finished in 0.0002 seconds (files took 0.0351 seconds to
    load)
    0 examples, 0 failures
    

Shoulda Matchers

  • Shoulda Matchers provides useful one-liners for common tests.

  • Add shoulda-matchers to test group of Gemfile

    group :test do
      gem 'shoulda-matchers'
    end
    
    • Then install it with command bundle install
  • To integrate it to spec add following to bottom of the rails_helper.rb

    Shoulda::Matchers.configure do |config|
      config.integrate do |with|
        with.test_framework :rspec
        with.library :rails
      end
    end
    

FactoryBot

  • Add factory_bot_rails to Gemfile. We want this gem to available on all rails environments, add this gem on outside of any group blocks.

    gem 'factory_bot_rails'
    
    • Then install it with command bundle install
  • To use FactoryBot inside the spec file require it in spec_helper.rb file

    require 'factory_bot_rails'
    
  • Then in same file, inside of RSpec.configure block add following line to use FactoryBot methods without FactoryBot namespace. For example we have to do FactoryBot.create we can instead just use the create method directly

    config.include FactoryBot::Syntax::Methods
    
  • we want Rails model generator to use FactoryBot to create factory file stubs whenever we generate a new model. For this, require FactoryBot on the top of config/application.rb

    require 'factory_bot_rails'
    
  • Then in the same file add following code inside the Application class

    config.generators do |g|
      g.test_framework :rspec, fixture: true
      g.fixture_replacement :factory_bot, dir: 'spec/factories'
    end
    

Now RSpec, Shoulda Matchers, and FactoryBot are all set up and ready to help test your Rails application!

Top comments (0)