Skip to content

Add documentation and feature test on headers setup in controller spec #2229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions features/controller_specs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,19 @@ To specify outcomes, you can use:
* by default, views are not rendered. See
[views are stubbed by default](controller-specs/views-are-stubbed-by-default) and
[render_views](controller-specs/render-views) for details.

## Headers

We encourage you to use [request specs](https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec) if you want to set headers in your call. If you still want to use controller specs with custom http headers you can use `request.headers`:

require "rails_helper"

RSpec.describe TeamsController, type: :controller do
describe "GET index"
it "returns a 200" do
request.headers["Authorization"] = "foo"
get :show
expect(response).to have_http_status(:ok)
end
end
end
49 changes: 49 additions & 0 deletions features/controller_specs/setting_request_headers.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
Feature: Setting request headers

We recommend you to switch to request specs instead of controller specs if you want to set
headers in your call. If you still want to set headers in controller specs, you can use
`request.headers` as mentioned bellow.

Scenario: Setting a header value in a controller spec
Given a file named "spec/controllers/application_controller_spec.rb" with:
"""ruby
require "rails_helper"

RSpec.describe ApplicationController, type: :controller do
controller do
def show
if request.headers["Authorization"] == "foo"
head :ok
else
head :forbidden
end
end
end

before do
routes.draw { get "show" => "anonymous#show" }
end

context "valid Authorization header" do
it "returns a 200" do
request.headers["Authorization"] = "foo"

get :show

expect(response).to have_http_status(:ok)
end
end

context "invalid Authorization header" do
it "returns a 403" do
request.headers["Authorization"] = "bar"

get :show

expect(response).to have_http_status(:forbidden)
end
end
end
"""
When I run `rspec spec`
Then the example should pass