设置请求头

如果您想在调用中设置标头,我们建议您切换到请求规范而不是控制器规范。 如果您仍然想在控制器规范中设置标头,您可以像下面提到的那样使用 `request.headers`。

在控制器规范中设置标头值

假设有一个名为 “spec/controllers/applicationcontrollerspec.rb” 的文件,其中包含

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

我运行 `rspec spec`

那么该示例应该通过。