Set up RSpec, Shoulda matchers and FactoryBot on Rails 7
April 27, 2025
This was originally published on Dev.to
Rspec
-
Add
rspec-railson development and test group of Gemfilegroup :development, :test do gem 'rspec-rails' end- Then install it with command
bundle install
- Then install it with command
-
Run command
rails generate rspec:installfor 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 rspecyou 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-matchersto test group of Gemfilegroup :test do gem 'shoulda-matchers' end- Then install it with command
bundle install
- Then install it with command
-
To integrate it to spec add following to bottom of the
rails_helper.rbShoulda::Matchers.configure do |config| config.integrate do |with| with.test_framework :rspec with.library :rails end end
FactoryBot
-
Add
factory_bot_railsto 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
- Then install it with command
-
To use
FactoryBotinside the spec file require it inspec_helper.rbfilerequire 'factory_bot_rails' -
Then in same file, inside of
RSpec.configureblock add following line to useFactoryBotmethods withoutFactoryBotnamespace. For example we have to doFactoryBot.createwe can instead just use thecreatemethod directlyconfig.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
FactoryBoton the top ofconfig/application.rbrequire 'factory_bot_rails' -
Then in the same file add following code inside the
Applicationclassconfig.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!