Rails RSpec Setup

2018-02-08 10:20:14来源:oschina作者:Kolosek人点击


RSpec is an awesome tool for testing Rails apps. It is a hugely popular BDD-oriented (BehaviorDrivenDevelopment) testing framework in the Ruby community.

It makes writing tests simpler, more expressive and easier to maintain!

Getting started

First, you'll need to install RSpec but you’ll also needDatabase Cleanerto help hold things together and ensure a clean state during tests. Add the following gems to the :test and :development groups in your Gemfile and then runbundle install:

group :development, :test do
gem "database_cleaner"
gem "rspec-rails"
endConfiguring RSpec

Before you can start with writing your RSpec tests your will need to runrails generate rspec:install. This will create the following files:


Files such as spec_helper.rbandrails_helper.rbcontain the default RSpec set up with lots of comments. It isstronglyrecommended to read through all of those comments to get a good understanding of what each option does.


spec_helper.rb file is used to configure RSpec. The base configuration file, after uncommenting some useful configuration options, is written in the following way:

RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
config.shared_context_metadata_behavior = :apply_to_host_groups
config.filter_run_when_matching :focus
config.disable_monkey_patching!if config.files_to_run.one?
config.default_formatter = "doc"
endconfig.profile_examples = 10config.order = :random
Kernel.srand config.seed
expectations.include_chain_clauses_in_custom_matcher_descriptions = true-Chain methodallows custom matcher descriptions and failure messages to include text for helper methods.
mocks.verify_partial_doubles = true-Partial doublesprevent you from stubbing any methods that don’t already exist on an object, it typo-proofs your mocks.
config.shared_context_metadata_behavior = :apply_to_host_groups-Shared context metadataconfigures how RSpec treats metadata passed as part of a shared example group definition.
filter_run_when_matching-Filter run when matchingallows you to limit a spec run to individual examples or groups you tagged with:focusmetadata.
disable_monkey_patching!-Prevents RSpec from monkey patchingmakes objects behave in tests as they would in "real" life.
default_formatter-Default formattersets up the default format of your rspec tests that will be used if no formatter has been set.
config.profile_examples-Profile examplesprint the slowest examples and example groups at the end of the spec run, but it slows down your suite
config.order = :randomandKernel.srand config.seed- Configure tests to run in arandom order. This helps to keep each test independent of one another. rails_helper.rb

rails_helper.rb file is used for specs which depend on Rails (nearly every part of a Rails projects). rails_helper.rb requires spec_helper.rb to work.

require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
fixture_path-File fixtureis a normal file stored in spec/fixtures by default.
use_transactional_fixtures-Transactionalfixtures allow records created for one test to be visible for the next test.
infer_spec_type_from_file_location!- Allows to automaticallytag specs in directorieswith matching type metadata so that they have relevant helpers available to them.
filter_rails_from_backtrace!-Backtrace filteringis used to filter out lines in backtraces that come from Rails gems in order to reduce the noise in test failure output. Configuring Database Cleaner

By configuring theDatabase Cleanerin your application, you make it sure that tests start with a clean state. The only thing you need to do is to add the following to your RSpec.configure block in rails_helper.rb:

config.before(:suite) do
endHow to run the tests?

Once everything is configured you are ready to go! There are four ways to run your test:

Everything at once:bundle exec rspec. This runs all your tests.
One RSpec package:bundle exec rspec ./spec/models This runs all model specs.
One RSpec file at a time:bundle exec rspec ./spec/models/story_spec.rb. This runs only tests in Story model.
One by one:bundle exec rspec ./spec/models/story_spec.rb:10 This runs only tests on line 10 in Story model.

Be careful! The more tests there are the longer it takes to compile them. Only run tests for what you really need!

We hope this article helped you get your tests up and running!

Originally published on kolosek.com .