rspec-rails Build Status Code Climate

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

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

Installation

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

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

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 => "git://github.com/rspec/#{lib}.git", :branch => 'master'
end

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:

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

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

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.

Generators

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.

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])
  end
end

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)
    end
    it "renders the index template" do
      get :index
      expect(response).to render_template("index")
    end
    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])
    end
  end
end

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"
    end
    post "/login", :username => "jdoe", :password => "secret"
    assert_select ".header .username", :text => "jdoe"
  end
end

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")
  end
end

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.

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)])
    render
    expect(view).to render_template(:partial => "_event", :count => 2)
  end
end
RSpec.describe "events/show", :type => :view do
  it "displays the event location" do
    assign(:event, Event.new(:location => "Chicago"))
    render
    expect(rendered).to include("Chicago")
  end
end

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:

assign(:widget, Widget.new)
render

The code above assigns Widget.new 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 = Widget.new
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)

rendered

This represents the rendered view.

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

Upgrade note

# rspec-rails-1.x
render
response.should xxx
# rspec-rails-2.x+
render
rendered.should xxx
# rspec-rails-2.x+ with expect syntax
render
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"
    )
  end
  it "does not expose a list of profiles" do
    expect(:get => "/profiles").not_to be_routable
  end
end

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 = Event.new("Ruby Kaigi", Date.new(2010, 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/
    end
  end
end

Matchers

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

be_a_new

expect(object).to be_a_new(Widget)

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

render_template

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 } )

redirect_to

expect(response).to redirect_to(widgets_path)

route_to

expect(:get => "/widgets").to route_to(:controller => "widgets", :action => "index")

be_routable

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

have_http_status

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:

task("spec").clear

Contribute

See http://github.com/rspec/rspec-dev.

For rspec-rails-specific development information, see README_DEV.

Also see

Feature Requests & Bugs

See http://github.com/rspec/rspec-rails/issues