Ruby Cucumber Shell Other
Latest commit 063f035 Oct 18, 2016 @sgerrand sgerrand committed with JonRowe Adds documentation and feature for job specs (#1725)
* Add documentation for ActiveJob specs

Updates existing documentation with a section on job specs and adds a
related cucumber feature.

* Add failing example for configuration error

Job specs must be set up with the correct queue adapter, otherwise an
exception will be thrown. Adding an additional step definition allows
this scenario to be tested.

* Updates top level documentation for job specs

Applying [PR feedback](#1725 (comment)).
Failed to load latest commit information.
benchmarks Include the benchmark from #1308. [ci skip] Mar 10, 2015
example_app_generator Add active_support to the app generator Apr 1, 2016
features Adds documentation and feature for job specs (#1725) Oct 18, 2016
lib Improve failure message for AJ matcher (#1722) Oct 12, 2016
script Updated travis build scripts (from rspec-dev) (#1639) Jun 15, 2016
spec Improve failure message for AJ matcher (#1722) Oct 12, 2016
yard/template/default rdoc Dec 8, 2011
.document correct case of license Oct 7, 2015
.gitignore Ignore specs.out since our build scripts produce that as an artifact.… Jul 10, 2015
.rspec Use default `.rspec` configuration. May 23, 2015
.rubocop.yml Adjust rubocop config for rspec-support. Aug 16, 2014
.rubocop_rspec_base.yml Updated travis build scripts (from rspec-dev) (#1639) Jun 15, 2016
.travis.yml Test against rails 5 proper (#1648) Jul 1, 2016
.yardopts correct case of license Oct 7, 2015 Updated common markdown files (from rspec-dev) [ci skip] Dec 7, 2015 Updated common markdown files (from rspec-dev) [ci skip] Dec 7, 2015 Updated common markdown files (from rspec-dev) [ci skip] Dec 7, 2015 Update to deal with rspec-core :example_group metadata changes. Mar 15, 2014 Changelog for #1722 Oct 12, 2016 Updated common markdown files (from rspec-dev) [ci skip] Dec 7, 2015
Gemfile Restrict mime-types version for older rubies Mar 24, 2016
Gemfile-custom.sample Gemfile-custom updates Sep 12, 2012
Gemfile-rails-dependencies force rails gems to be the same version as rails for maintenance bran… Oct 6, 2016
Gemfile-rspec-dependencies Move common rspec dependencies into custom Gemfile Jun 24, 2014 list copyrights Oct 6, 2015 Adds documentation and feature for job specs (#1725) Oct 18, 2016 Freshens up the development documentation Jun 25, 2013
Rakefile Add --skip-listen flag when generating Rails apps Mar 28, 2016
Thorfile Uses Thor actions where possible May 24, 2013
appveyor.yml Updated travis build scripts (from rspec-dev) (#1639) Jun 15, 2016
cucumber.yml more profiles Apr 28, 2010
maintenance-branch Add maintenance-branch for master. Jun 9, 2014
rspec-rails.gemspec Update gem description to include Rails 5. Jul 4, 2016

rspec-rails Build Status Code Climate

rspec-rails is a testing framework for Rails 3.x, 4.x and 5.0.

Use rspec-rails 1.x for Rails 2.x.


Add rspec-rails to both the :development and :test groups in the Gemfile:

group :development, :test do
  gem 'rspec-rails', '~> 3.5'

Want to run against the master branch? You'll need to include the dependent RSpec repos as well. Add the following to your Gemfile:

%w[rspec-core rspec-expectations rspec-mocks rspec-rails rspec-support].each do |lib|
  gem lib, :git => "{lib}.git", :branch => 'master'

Download and install by running:

bundle install

Initialize the spec/ directory (where specs will reside) with:

rails generate rspec:install

This adds the following files which are used for configuration:

  • .rspec
  • spec/spec_helper.rb
  • spec/rails_helper.rb

Check the comments in each file for more information.

Use the rspec command to run your specs:

bundle exec rspec

By default the above will run all _spec.rb files in the spec directory. For more details about this see the RSpec spec file docs.

To run only a subset of these specs use the following command:

# Run only model specs
bundle exec rspec spec/models

# Run only specs for AccountsController
bundle exec rspec spec/controllers/accounts_controller_spec.rb

# Run only spec on line 8 of AccountsController
bundle exec rspec spec/controllers/accounts_controller_spec.rb:8

Specs can also be run via rake spec, though this command may be slower to start than the rspec command.

In Rails 4, you may want to create a binstub for the rspec command so it can be run via bin/rspec:

bundle binstubs rspec-core

Upgrade Note

For detailed information on the general RSpec 3.x upgrade process see the RSpec Upgrade docs.

There are three particular rspec-rails specific changes to be aware of:

  1. The default helper files created in RSpec 3.x have changed
  2. File-type inference disabled by default
  3. Rails 4.x ActiveRecord::Migration pending migration checks
  4. Extraction of stub_model and mock_model to rspec-activemodel-mocks
  5. In Rails 5.x, controller testing has been moved to its own gem which is rails-controller-testing. Using assigns in your controller specs without adding this gem will no longer work.

Please see the RSpec Rails Upgrade docs for full details.

NOTE: Generators run in RSpec 3.x will now require rails_helper instead of spec_helper.


Once installed, RSpec will generate spec files instead of Test::Unit test files when commands like rails generate model and rails generate controller are used.

You may also invoke RSpec generators independently. For instance, running rails generate rspec:model will generate a model spec. For more information, see list of all generators.


Once you've set up the environment, you'll need to cd into the working directory of whichever repo you want to work in. From there you can run the specs and cucumber features, and make patches.

NOTE: You do not need to use rspec-dev to work on a specific RSpec repo. You can treat each RSpec repo as an independent project. Please see the following files:

For rspec-rails-specific development information, see

Model Specs

Use model specs to describe behavior of models (usually ActiveRecord-based) in the application.

Model specs default to residing in the spec/models folder. Tagging any context with the metadata :type => :model treats its examples as model specs.

For example:

require "rails_helper"

RSpec.describe User, :type => :model do
  it "orders by last name" do
    lindeman = User.create!(first_name: "Andy", last_name: "Lindeman")
    chelimsky = User.create!(first_name: "David", last_name: "Chelimsky")

    expect(User.ordered_by_last_name).to eq([chelimsky, lindeman])

For more information, see cucumber scenarios for model specs.

Controller Specs

Use controller specs to describe behavior of Rails controllers.

Controller specs default to residing in the spec/controllers folder. Tagging any context with the metadata :type => :controller treats its examples as controller specs.

For example:

require "rails_helper"

RSpec.describe PostsController, :type => :controller do
  describe "GET #index" do
    it "responds successfully with an HTTP 200 status code" do
      get :index
      expect(response).to be_success
      expect(response).to have_http_status(200)

    it "renders the index template" do
      get :index
      expect(response).to render_template("index")

    it "loads all of the posts into @posts" do
      post1, post2 = Post.create!, Post.create!
      get :index

      expect(assigns(:posts)).to match_array([post1, post2])

For more information, see cucumber scenarios for controller specs.

Note: To encourage more isolated testing, views are not rendered by default in controller specs. If you are verifying discrete view logic, use a view spec. If you are verifying the behaviour of a controller and view together, consider a request spec. You can use render_views if you must verify the rendered view contents within a controller spec, but this is not recommended.

Request Specs

Use request specs to specify one or more request/response cycles from end to end using a black box approach.

Request specs default to residing in the spec/requests, spec/api, and spec/integration directories. Tagging any context with the metadata :type => :request treats its examples as request specs.

Request specs mix in behavior from ActionDispatch::Integration::Runner, which is the basis for Rails' integration tests.

require 'rails_helper'

RSpec.describe "home page", :type => :request do
  it "displays the user's username after successful login" do
    user = User.create!(:username => "jdoe", :password => "secret")
    get "/login"
    assert_select "form.login" do
      assert_select "input[name=?]", "username"
      assert_select "input[name=?]", "password"
      assert_select "input[type=?]", "submit"

    post "/login", :username => "jdoe", :password => "secret"
    assert_select ".header .username", :text => "jdoe"

The above example uses only standard Rails and RSpec APIs, but many RSpec/Rails users like to use extension libraries like FactoryGirl and Capybara:

require 'rails_helper'

RSpec.describe "home page", :type => :request do
  it "displays the user's username after successful login" do
    user = FactoryGirl.create(:user, :username => "jdoe", :password => "secret")
    visit "/login"
    fill_in "Username", :with => "jdoe"
    fill_in "Password", :with => "secret"
    click_button "Log in"

    expect(page).to have_selector(".header .username", :text => "jdoe")

FactoryGirl decouples this example from changes to validation requirements, which can be encoded into the underlying factory definition without requiring changes to this example.

Among other benefits, Capybara binds the form post to the generated HTML, which means we don't need to specify them separately. Note that Capybara's DSL as shown is, by default, only available in specs in the spec/features directory. For more information, see the Capybara integration docs.

There are several other Ruby libs that implement the factory pattern or provide a DSL for request specs (a.k.a. acceptance or integration specs), but FactoryGirl and Capybara seem to be the most widely used. Whether you choose these or other libs, we strongly recommend using something for each of these roles.

Feature Specs

Feature specs test your application from the outside by simulating a browser. capybara is used to manage the simulated browser.

Feature specs default to residing in the spec/features folder. Tagging any context with the metadata :type => :feature treats its examples as feature specs.

Feature specs mix in functionality from the capybara gem, thus they require capybara to use. To use feature specs, add capybara to the Gemfile:

gem "capybara"

For more information, see the cucumber scenarios for feature specs.

Mailer specs

By default Mailer specs reside in the spec/mailers folder. Adding the metadata :type => :mailer to any context makes its examples be treated as mailer specs.

ActionMailer::TestCase::Behavior is mixed into your mailer specs.

require "rails_helper"

RSpec.describe Notifications, :type => :mailer do
  describe "notify" do
    let(:mail) { Notifications.signup }

    it "renders the headers" do
      expect(mail.subject).to eq("Signup")
      expect( eq([""])
      expect(mail.from).to eq([""])

    it "renders the body" do
      expect(mail.body.encoded).to match("Hi")

For more information, see the cucumber scenarios for mailer specs .

Job specs

Tagging a context with the metadata :type => :job treats its examples as job specs. Typically these specs will live in spec/jobs.

require 'rails_helper'

RSpec.describe UploadBackupsJob, :type => :job do
  describe "#perform_later" do
    it "uploads a backup" do
      ActiveJob::Base.queue_adapter = :test
      expect(UploadBackupsJob).to have_been_enqueued

For more information, see the cucumber scenarios for job specs .

View specs

View specs default to residing in the spec/views folder. Tagging any context with the metadata :type => :view treats its examples as view specs.

View specs mix in ActionView::TestCase::Behavior.

require 'rails_helper'

RSpec.describe "events/index", :type => :view do
  it "renders _event partial for each event" do
    assign(:events, [double(Event), double(Event)])
    expect(view).to render_template(:partial => "_event", :count => 2)

RSpec.describe "events/show", :type => :view do
  it "displays the event location" do
    assign(:event, => "Chicago"))
    expect(rendered).to include("Chicago")

View specs infer the controller name and path from the path to the view template. e.g. if the template is events/index.html.erb then:

controller.controller_path == "events"
controller.request.path_parameters[:controller] == "events"

This means that most of the time you don't need to set these values. When spec'ing a partial that is included across different controllers, you may need to override these values before rendering the view.

To provide a layout for the render, you'll need to specify both the template and the layout explicitly. For example:

render :template => "events/show", :layout => "layouts/application"

assign(key, val)

Use this to assign values to instance variables in the view:


The code above assigns to the @widget variable in the view, and then renders the view.

Note that because view specs mix in ActionView::TestCase behavior, any instance variables you set will be transparently propagated into your views (similar to how instance variables you set in controller actions are made available in views). For example:

@widget =
render # @widget is available inside the view

RSpec doesn't officially support this pattern, which only works as a side-effect of the inclusion of ActionView::TestCase. Be aware that it may be made unavailable in the future.

Upgrade note

# rspec-rails-1.x
assigns[key] = value

# rspec-rails-2.x+
assign(key, value)


This represents the rendered view.

expect(rendered).to match /Some text expected to appear on the page/

Upgrade note

# rspec-rails-1.x
response.should xxx

# rspec-rails-2.x+
rendered.should xxx

# rspec-rails-2.x+ with expect syntax
expect(rendered).to xxx

Routing specs

Routing specs default to residing in the spec/routing folder. Tagging any context with the metadata :type => :routing treats its examples as routing specs.

require 'rails_helper'

RSpec.describe "routing to profiles", :type => :routing do
  it "routes /profile/:username to profile#show for username" do
    expect(:get => "/profiles/jsmith").to route_to(
      :controller => "profiles",
      :action => "show",
      :username => "jsmith"

  it "does not expose a list of profiles" do
    expect(:get => "/profiles").not_to be_routable

Upgrade note

route_for from rspec-rails-1.x is gone. Use route_to and be_routable instead.

Helper specs

Helper specs default to residing in the spec/helpers folder. Tagging any context with the metadata :type => :helper treats its examples as helper specs.

Helper specs mix in ActionView::TestCase::Behavior. A helper object is provided which mixes in the helper module being spec'd, along with ApplicationHelper (if present).

require 'rails_helper'

RSpec.describe EventsHelper, :type => :helper do
  describe "#link_to_event" do
    it "displays the title, and formatted date" do
      event ="Ruby Kaigi",, 8, 27))
      # helper is an instance of ActionView::Base configured with the
      # EventsHelper and all of Rails' built-in helpers
      expect(helper.link_to_event).to match /Ruby Kaigi, 27 Aug, 2010/


Several domain-specific matchers are provided to each of the example group types. Most simply delegate to their equivalent Rails' assertions.


  • Available in all specs
  • Primarily intended for controller specs
expect(object).to be_a_new(Widget)

Passes if the object is a Widget and returns true for new_record?


  • Delegates to Rails' assert_template
  • Available in request, controller, and view specs

In request and controller specs, apply to the response object:

expect(response).to render_template("new")

In view specs, apply to the view object:

expect(view).to render_template(:partial => "_form", :locals => { :widget => widget } )


  • Delegates to assert_redirect
  • Available in request and controller specs
expect(response).to redirect_to(widgets_path)


  • Delegates to Rails' assert_routing
  • Available in routing and controller specs
expect(:get => "/widgets").to route_to(:controller => "widgets", :action => "index")


Passes if the path is recognized by Rails' routing. This is primarily intended to be used with not_to to specify standard CRUD routes which should not be routable.

expect(:get => "/widgets/1/edit").not_to be_routable


  • Passes if response has a matching HTTP status code
  • The following symbolic status codes are allowed:
    • Rack::Utils::SYMBOL_TO_STATUS_CODE
    • One of the defined ActionDispatch::TestResponse aliases:
      • :error
      • :missing
      • :redirect
      • :success
  • Available in controller, feature, and request specs.

In controller and request specs, apply to the response object:

expect(response).to have_http_status(201)
expect(response).not_to have_http_status(:created)

In feature specs, apply to the page object:

expect(page).to have_http_status(:success)

rake tasks

Several rake tasks are provided as a convenience for working with RSpec. To run the entire spec suite use rake spec. To run a subset of specs use the associated type task, for example rake spec:models.

A full list of the available rake tasks can be seen by running rake -T | grep spec.

Customizing rake tasks

If you want to customize the behavior of rake spec, you may define your own task in the Rakefile for your project. However, you must first clear the task that rspec-rails defined:


Also see

Feature Requests & Bugs