控制器规格

控制器规格通过 `type: :controller` 标记,或者如果设置了 `config.infer_spec_type_from_file_location!`,则将其放在 `spec/controllers` 中。

控制器规格是 Rails 功能测试的 RSpec 包装器 (ActionController::TestCase::Behavior)。它允许您在每个示例中模拟单个 HTTP 请求,然后指定预期结果,例如

要指定结果,您可以使用

示例

RSpec.describe TeamsController do
  describe "GET index" do
    it "assigns @teams" do
      team = Team.create
      get :index
      expect(assigns(:teams)).to eq([team])
    end

    it "renders the index template" do
      get :index
      expect(response).to render_template("index")
    end
  end
end

视图

标头

如果您想在调用中设置标头,我们建议您使用 请求规格。如果您仍然想使用带自定义 HTTP 标头的控制器规格,可以使用 request.headers

require "rails_helper"

RSpec.describe TeamsController, type: :controller do
  describe "GET index" do
    it "returns a 200" do
      request.headers["Authorization"] = "foo"
      get :show
      expect(response).to have_http_status(:ok)
    end
  end
end

主题