skip to content

Spec Types & Matchers

rspec-rails wires RSpec into Rails: rails_helper, spec types such as request, model and system, and Rails matchers. Interviewers ask why request specs replaced controller specs.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

With rspec-rails 8, why do request specs replace controller specs for a time-sheet JSON API, and what does each one exercise?

level: middleimportance: must knowfreq 68%

answer

  1. machine client, verb plus path
  2. router and middleware vs one action
  3. type: :request wraps IntegrationTest
  4. assigns lives in rails-controller-testing
  5. have_http_status(:unprocessable_content)

basics

~20 s

Request specs send a real verb and path through Rails' router, middleware and controller, like ActionDispatch::IntegrationTest. Controller specs call one action directly. Since RSpec 3.5 both teams recommend request specs; assigns and render_template need the rails-controller-testing gem.

solid answer

~40 s

A request spec (`type: :request`) wraps `ActionDispatch::IntegrationTest`: `post "/time_entries", params: {...}, as: :json` goes through routing, the middleware stack, the controller, rendering and Rails' exception handling, and you assert on `response` with `have_http_status(:created)` and `response.parsed_body`. A controller spec (`type: :controller`) wraps `ActionController::TestCase`: `post :create` names the action, skips the middleware and stubs views unless `render_views` is on. That isolation tests implementation details, such as which instance variables were set, and those helpers (`assigns`, `assert_template`) were extracted to the `rails-controller-testing` gem in Rails 5. Since RSpec 3.5 the Rails and RSpec teams recommend request specs, and the rspec-rails scaffold generator writes request specs by default and controller specs only with `--controller-specs`.

code

ruby · 17 lines
ruby
# Controller spec (older style) -- action name, no router, views stubbed
RSpec.describe TimeEntriesController, type: :controller do
  it "assigns the entries" do
    get :index
    # NoMethodError unless the rails-controller-testing gem is installed
    expect(assigns(:time_entries)).to eq(TimeEntry.all.to_a)
  end
end

# Request spec -- verb and path through the whole stack
RSpec.describe "Time entries", type: :request do
  it "lists entries as JSON" do
    get "/time_entries", as: :json
    expect(response).to have_http_status(:ok)
    expect(response.parsed_body).to be_an(Array)
  end
end

go deeper

for a junior

Know that a request spec sends a verb and path and checks the response, and write one with type: :request and have_http_status.

for a middle

Explain which Rails test class each spec type wraps, what the router and middleware add, and why assigns and render_template moved to a separate gem.

for a senior

Argue for request specs on an API from failure modes: missing routes, before_action filters, parameter parsing and rescuable exceptions that a controller spec never sees.

for a principal

Set a team policy for migrating a legacy controller-spec suite: what to rewrite first, what to delete, and how system specs and request specs split the coverage.

## Two spec types for the same controller rspec-rails offers two ways to test a controller, and they sit on two different Rails test classes: | | Request spec | Controller spec | |---|---|---| | Metadata | `type: :request` | `type: :controller` | | Rails class underneath | `ActionDispatch::IntegrationTest` | `ActionController::TestCase` | | How you call it | `get "/time_entries/7"` (verb plus path) | `get :show, params: { id: 7 }` (action name) | | Router | recognises the path | bypassed | | Middleware stack | runs | skipped | | Views | rendered | stubbed unless `render_views` | | Typical assertions | status, body, headers, redirects | status, `assigns`, `render_template` | A **request spec** behaves like a machine client: it sends an HTTP verb, a path, parameters and headers into the application and checks the response. A **controller spec** constructs a test request, hands it straight to one controller action and lets you inspect what the action did inside. ## Why request specs won Since RSpec 3.5, the release that added Rails 5 support, both the Rails and RSpec teams discourage testing controllers directly in favour of request specs. The reasons interviewers expect: - **They test the contract, not the wiring.** A time-sheet API is a set of URLs and JSON payloads. A request spec fails when the route, a `before_action`, parameter parsing or the response shape breaks; a controller spec can pass while the route does not exist. - **The middleware stack is in play.** Request specs exercise what a real client meets: parameter parsing for `as: :json`, cookies and sessions, and Rails' exception handling. The generated test environment sets `config.action_dispatch.show_exceptions = :rescuable`, so a request for a missing `TimeEntry` gets a 404 response rather than an exception in the spec. - **The internal assertions went away.** Rails 5 extracted `assigns` and `assert_template` into the `rails-controller-testing` gem; without it they raise `NoMethodError` with a message naming the gem. Those assertions tied tests to instance variable names. The generators reflect this: rspec-rails' `scaffold` and `controller` generators default to `request_specs: true` and `controller_specs: false`. ## A request spec for a time-sheet API ```ruby require "rails_helper" RSpec.describe "Time entries API", type: :request do it "creates an entry" do post "/time_entries", params: { time_entry: { minutes: 90, project_id: projects(:billing).id } }, as: :json expect(response).to have_http_status(:created) expect(response.parsed_body["minutes"]).to eq(90) end it "rejects an entry without minutes" do post "/time_entries", params: { time_entry: { minutes: nil } }, as: :json expect(response).to have_http_status(:unprocessable_content) end end ``` Points worth naming: - `as: :json` encodes the params as a JSON body (a query string for `get`) and sets both the `Content-Type` and `Accept` headers to JSON, the way a real API client would. - `response.parsed_body` parses a JSON body into a hash with indifferent access, so string and symbol keys both work; since Rails 7.1 it also supports pattern matching. - `have_http_status` accepts a number, a Rack status symbol, or a generic group: `:success` (2xx), `:redirect` (3xx), `:missing` (404) and `:error` (5xx). ## Status symbols on Rails 8.1 Rails 8.1 runs on Rack 3.x, where the canonical name for 422 is `:unprocessable_content`. `:unprocessable_entity` is Rack's obsolete name: it still resolves to 422 but Rack 3.2 prints a deprecation warning. rspec-rails 8.0.2 fixed its scaffold generator so the specs it writes use the current symbol. ## What each one can miss - A **controller spec** passes when the route is missing or points at another action, when a middleware rejects the request, and when the JSON template would raise, because views are stubbed. - A **request spec** does not check which instance variables or templates were used. That is deliberate: it tests what the client receives. - **Neither** runs JavaScript or a browser. Browser flows belong in system specs, which drive the app through Capybara. ## When a controller spec still appears Controller specs still work in rspec-rails 8 and you will meet them in older suites. Reasons to keep one are narrow: testing an anonymous controller defined in the spec to exercise a concern, or a legacy suite where rewriting is not worth it. New code gets request specs, plus a few system specs for browser flows.

  • What does have_http_status(:error) match in a request spec?
    Only 5xx responses. rspec-rails maps `:error` to `server_error?`, `:success` to 2xx, `:redirect` to 3xx and `:missing` to 404. A 422 from a failed save is not an `:error`; assert it with `have_http_status(:unprocessable_content)` or `422`.
  • Why can a request for a missing record return 404 in a request spec instead of raising?
    The generated `config/environments/test.rb` sets `config.action_dispatch.show_exceptions = :rescuable`. Exceptions listed in Rails' rescue responses, such as `ActiveRecord::RecordNotFound`, are rendered as their status by the exception middleware, which request specs run through. Other exceptions still raise into the spec.
  • How does a request spec authenticate a user for the time-sheet API?
    The same way a client does: send the credential the app expects, for example an `Authorization` header in `headers:`, or post to the sign-in path first so the session cookie carries over to later requests in the example. Gem-specific sign-in helpers belong to the auth library in use.

  • Controller specs are faster, so they are the recommended default
  • have_http_status(:error) matches a 422 validation failure
  • assigns works in any rspec-rails 8 controller spec without extra gems
  • Request specs skip the router and call the action directly
  • :unprocessable_entity is the current Rack name for 422

Assumes rspec-rails 8.0 on Rails 8.1 and Rack 3.2, where 422 is :unprocessable_content and :unprocessable_entity is the obsolete, warning name.

open as a page

In a Rails 8.1 app, what does bin/rails generate rspec:install create, and why do Rails specs require rails_helper instead of spec_helper?

level: juniorimportance: should knowfreq 46%

basics

~10 s

rspec:install writes .rspec, spec/spec_helper.rb and spec/rails_helper.rb. spec_helper configures plain RSpec without Rails; rails_helper loads config/environment, requires rspec/rails and sets fixtures and transactions, so any spec touching Rails code requires rails_helper.

open as a page

In rspec-rails, how do the have_enqueued_job and have_been_enqueued matchers differ, and what must the Active Job adapter be for either to work?

level: middleimportance: should knowfreq 44%

basics

~20 s

have_enqueued_job is a block matcher counting jobs enqueued inside expect { }; have_been_enqueued checks a job class against everything the adapter holds. Both raise unless ActiveJob::Base.queue_adapter is the test adapter, which a Rails test environment uses when nothing else is configured.

open as a page

In rspec-rails 8, how does a spec get its type, and what breaks when infer_spec_type_from_file_location! stays commented out?

level: middleimportance: should knowfreq 38%

basics

~20 s

rspec-rails mixes helpers into an example group by its type: metadata. New rails_helper files leave infer_spec_type_from_file_location! commented out, so a spec in spec/requests without type: :request has no get or post and fails with NoMethodError.

open as a page

In an rspec-rails suite, what does config.use_transactional_fixtures = true do to each example, and which cases still leave rows behind or need it off?

level: seniorimportance: should knowfreq 34%

basics

~20 s

use_transactional_fixtures = true wraps every example in a database transaction that is rolled back afterwards, sharing one pinned connection across threads. Rows written in before(:context), by another process or by code needing separate connections escape it; those cases need it off.

open as a page