Cesare's Blog

Cesare's Blog

Switching Rails test framework to Rspec

Switching Rails test framework to Rspec

How to change the test framework of an existing Rails application to Rspec

I had an old Rails application that was generated with the default Minitest framework for testing. Now I want to keep working on it but switching to Rspec. The application has no tests, but we do have a test directory with default boilerplate.

Setting up Rspec

Add the following gems to the Gemfile in the development and test block:

# Gemfile

group :development, :test do
  gem 'rspec-rails', '~> 5.0', '>= 5.0.1'
  gem 'factory_bot_rails', '~> 6.2'

Save the Gemfile and run bundle install.

Run the RSpec generator:

$ bundle exec rails generate rspec:install

The command adds the following files:


Since I won't be using fixtures, I can remove the fixture configuration line in the rails_helper.rb file:

# spec/rails_helper.rb

  # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
  config.fixture_path = "#{::Rails.root}/spec/fixtures"

Inside the configuration block, I include FactoryBot methods. This will allow me to call FactoryBot methods directly in the tests without prepending them with FactoryBot.

# spec/rails_helper.rb

  config.include FactoryBot::Syntax::Methods

Configure generators to use Rspec

In config/application.rb add:

config.generators.test_framework = :rspec

Remove minitest boilerplate.

git rm -r test/

The application is now ready to use RSpec.

Photo by Daniel Abadia on Unsplash

Share this