首页 > 解决方案 > RSpec 404 测试响应状态为 200

问题描述

我写了一个测试来测试 404 页面

pages_controller_spec.rb

RSpec.describe PagesController, type: :controller do
  before :all do
    Rails.application.config.action_dispatch.show_exceptions = true
    Rails.application.config.consider_all_request_local = false
  end

  describe "status 404" do
    it "respond with 404 if page is not found" do
      get :help, params: { id: "foobar" }
      expect(response.status).to eq(404)
    end
  end
end

页面控制器很简单,可以渲染静态页面“/help”和“/about”

class PagesController < ApplicationController
  def help
  end

  def about
  end
end

错误处理设置如下

application_controller.rb

 def not_found
   raise ActionController::RoutingError.new("Not Found")
 rescue
   render_404
 end

 def render_404
   render file: "#{Rails.root}/public/404", status: :not_found
 end

测试结果是

expected: 404
            got: 200

我不明白,因为“/help/foobar”在我自己在浏览器中尝试时会呈现 404 页面。我想问题可能是我在测试中的“获取”操作格式错误,但我不确定。

编辑

根据要求配置/routes.rb

  get "/about", to: "pages#about"
  get "/help", to: "pages#help"

编辑 2

使用https://relishapp.com/rspec/rspec-rails/v/3-4/docs/routing-specs/route-to-matcher中的语法更新了测试

测试现在看起来像这样

RSpec.describe PagesController, type: :controller do
  before :all do
    Rails.application.config.action_dispatch.show_exceptions = true
    Rails.application.config.consider_all_request_local = false
  end

  describe "status 404" do
    it "respond with 404 if page is not found" do
      expect(get("/foobar")).to route_to("application#not_found")
    end
  end
end

不幸的是,这引发了另一个错误

ActionController::UrlGenerationError:
 No route matches {:action=>"/foobar", :controller=>"pages"}

没有路线匹配这是重点,但由于某种原因正在使用“not_found”方法

标签: ruby-on-railsrspecrspec-rails

解决方案


更改您的路线以使您的呼叫从浏览器工作:

get "/help/:id", to: "pages#help"

如果测试返回 a 200,那是因为它直接help从控制器调用方法而不使用config/routes.rb文件。

编辑

以下是您测试路由的方法:https ://relishapp.com/rspec/rspec-rails/v/3-4/docs/routing-specs/route-to-matcher


推荐阅读