With rspec-rails 8, why do request specs replace controller specs for a time-sheet JSON API, and what does each one exercise?
answer
- machine client, verb plus path
- router and middleware vs one action
- type: :request wraps IntegrationTest
- assigns lives in rails-controller-testing
- have_http_status(:unprocessable_content)
basics
~20 sRequest 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 sA 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# 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
endgo deeper
Know that a request spec sends a verb and path and checks the response, and write one with type: :request and have_http_status.
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.
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.
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.