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.
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
If there is no test database, add it as follows.
config/database.yml
test:
<<: *default
database: db/test.sqlite3
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
$ 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
$ 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
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
$ bin/rails g rspec:model user
$ bin/rails g rspec:controller users
$ bin/rails g factory_bot:model user
$ bin/rails g rspec:feature users
Setup complete.