have_http_status 匹配器

have_http_status 匹配器用于指定响应返回所需的 状态码。它接受以下格式之一的单个参数

此匹配器适用于任何 response 对象。它可以在 控制器规格请求规格功能规格 中使用。

检查数字状态码

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

require "rails_helper"

RSpec.describe ApplicationController, type: :controller do

  controller do
    def index
      render :json => {}, :status => 209
    end
  end

  describe "GET #index" do
    it "returns a 209 custom status code" do
      get :index
      expect(response).to have_http_status(209)
    end
  end

end

我运行 rspec spec

那么示例应全部通过。

检查符号状态名称

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

require "rails_helper"

RSpec.describe ApplicationController, type: :controller do

  controller do
    def index
      render :json => {}, :status => :see_other
    end
  end

  describe "GET #index" do
    it "returns a :see_other status code" do
      get :index
      expect(response).to have_http_status(:see_other)
    end
  end

end

我运行 rspec spec

那么示例应全部通过。

检查符号通用状态类型

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

require "rails_helper"

RSpec.describe ApplicationController, type: :controller do

  controller do
    def index
      render :json => {}, :status => :bad_gateway
    end
  end

  describe "GET #index" do
    it "returns a some type of error status code" do
      get :index
      expect(response).to have_http_status(:error)
    end
  end

end

我运行 rspec spec

那么示例应全部通过。

在控制器规格中使用

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

require "rails_helper"

RSpec.describe GadgetsController, type: :controller do

  describe "GET #index" do
    it "returns a 200 OK status" do
      get :index
      expect(response).to have_http_status(:ok)
    end
  end

end

我运行 rspec spec/controllers/gadgets_spec.rb

那么示例应全部通过。

在请求规格中使用

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

require "rails_helper"

RSpec.describe "Widget management", type: :request do

  it "creates a Widget and redirects to the Widget's page" do
    get "/widgets/new"
    expect(response).to have_http_status(:ok)

    post "/widgets", :params => { :widget => {:name => "My Widget"} }
    expect(response).to have_http_status(302)

    follow_redirect!

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

end

我运行 rspec spec/requests

那么示例应全部通过。

在功能规格中使用

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

require "rails_helper"

RSpec.feature "Widget management", type: :feature do

  scenario "User creates a new widget" do
    visit "/widgets/new"
    expect(page).to have_http_status(200)

    click_button "Create Widget"

    expect(page).to have_http_status(:success)
  end

end

我运行 rspec spec/features/widget_management_spec.rb

那么示例应通过。