Rspec
-
Add
rspec-railson development and test group of Gemfile
group :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 Gemfile
group :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.rb
Shoulda::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.rbfile
require '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 directly
config.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.rb
require 'factory_bot_rails' -
Then in the same file add following code inside the
Applicationclass
config.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!
Top comments (1)
Thanks for the writeup, Ankit. Requiring FB in spec_helper is probably redundant, including in gemfile requires it by default.