Rspec
-
Add
rspec-rails
on 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:install
for 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 rspec
you 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-matchers
to 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_rails
to 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
FactoryBot
inside the spec file require it inspec_helper.rb
file
require 'factory_bot_rails'
-
Then in same file, inside of
RSpec.configure
block add following line to useFactoryBot
methods withoutFactoryBot
namespace. For example we have to doFactoryBot.create
we can instead just use thecreate
method 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
FactoryBot
on the top ofconfig/application.rb
require 'factory_bot_rails'
-
Then in the same file add following code inside the
Application
class
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.