Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brianjbayer/fb0f630ed3278ddd2c3e076474859d7f to your computer and use it in GitHub Desktop.
Save brianjbayer/fb0f630ed3278ddd2c3e076474859d7f to your computer and use it in GitHub Desktop.
Add the testing utility shoulda-matchers to your Rails project

Add and Configure shoulda-matchers To Your Rails RSpec Project

This guides you through adding the test expectation-matching utility shoulda-matchers to your Ruby on Rails RSpec project.

To install shoulda-matchers you will need to...

  1. Add the shoulda-matchers gem to your Rails RSpec project
  2. Configure shoulda-matchers to integrate with RSpec Rails

Add shoulda-matchers Gem to Your Rails RSpec Project

You need to add the shoulda-matchers gem to your Gemfile but really only need it for test.

  1. Edit your Gemfile and add gem 'shoulda-matchers' to just :test group, for example...

    group :test do
      gem 'shoulda-matchers'
    end
  2. Run bundle install to install the shoulda-matchers gem

    bundle install
    

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


Configure shoulda-matchers To Integrate With RSpec Rails

You need to configure shoulda-matchers to use RSpec Rails as the test framework.

You can add the shoulda-matchers 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/shoulda-matchers.rb file

    touch spec/support/config/shoulda-matchers.rb
  3. Edit your spec/support/config/shoulda-matchers.rb file to

    # frozen_string_literal: true
    
    Shoulda::Matchers.configure do |config|
      config.integrate do |with|
        with.test_framework :rspec
        with.library :rails
      end
    end
  4. Save your edited spec/support/config/shoulda-matchers.rb file

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

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

🏃 You should now be able to use the shoulda-matchers in your Rails specs.


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