shou2017.com
JP

Preparing RSpec for Rails

Fri Dec 1, 2017
Sat Aug 10, 2024

Since testing is important, I read a book about RSpec and summarized it here. I’m writing down the setup process as a memo so I won’t forget.

Everyday Rails - Introduction to Rails Testing with RSpec

Setting up RSpec.

Environment

  • Rails 5.1.1
  • Ruby 2.5.1
  • RSpec 3.6

Setup

In the past, you had to install various things, but starting with RSpec 3.6, the process has become much simpler.

Install rspec-rails and spring-commands-rspec to speed up the test suite startup time.

Gemfile

group :development, :test do
 gem 'rspec-rails', '~> 3.6.0'
 gem "factory_bot_rails"
end

group :development do
  gem 'spring-commands-rspec'
end

After adding the above to the Gemfile:

$ bundle install

Create a binstub:

$ bundle exec spring binstub rspec

Test Database

If there is no test database, add it as follows.

SQLite

config/database.yml
test:
  <<: *default
  database: db/test.sqlite3

MySQL or PostgreSQL

config/database.yml
test:
  <<: *default
  database: db/project_test
  Replace `project_test` with the appropriate name for your application.

Next, run the rake task to create a connectable database:

$ bin/rails db:create:all

RSpec Configuration

$ bin/rails g rspec:install
  Running via Spring preloader in process 2541
  create .rspec                   ← Configuration file for RSpec
  create spec                     ← Directory for spec files
  create spec/spec_helper.rb      ← Configuration file for RSpec
  create spec/rails_helper.rb

Change the RSpec output format from the default to documentation format (optional):

.rspec
--require spec_helper
--format documentation

Verification

$ bin/rspec
Running via Spring preloader in process 56846
No examples found.
Finished in 0.00074 seconds (files took 0.144553 seconds to load)
0 examples, 0 failures

Configure Generators to Avoid Creating Unnecessary Files

config/application.rb

require_relative 'boot'

require 'rails/all'

Bundler.require(*Rails.groups)

module Projects
  class Application < Rails::Application
    config.load_defaults 5.1
    config.generators do |g|
      g.test_framework :rspec,
      view_specs: false,
      helper_specs: false,
      routing_specs: false,
      request_specs: false
    end
  end
end

Creating a Model Spec

$ bin/rails g rspec:model user

Creating a Controller Spec (Controllers are often not tested)

$ bin/rails g rspec:controller users

Adding Factories to the Application

$ bin/rails g factory_bot:model user

Creating a Feature Spec

$ bin/rails g rspec:feature users

Setup complete.

Tags
RSpec
See Also