ruby-on-rails - 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”方法
解决方案
更改您的路线以使您的呼叫从浏览器工作:
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
推荐阅读
- java - java.lang.NoClassDefFoundError:在 spark-shell 中查询时出现 org/apache/hadoop/hive/ql/metadata/HiveException
- javascript - Facebook api 不返回电子邮件,而是返回其余的请求字段
- mysql - 保留查询中的 mysql 查询结果和变量集以供跨页面和会话使用
- python - 十进制到罗马转换程序在 Python 中给出错误答案
- parsing - Avro 多个枚举 int 相同类型(avro.SchemaParseException:无法重新定义)
- yaml - 如何根据给定的 openapi 3.0.3 yaml 文件生成 Quarkus rest JX-RS 服务
- c# - 通过反射解析字符串路径,如 WPF 绑定
- angular - 组件之间的角度和传递数据:解决保护与服务注入的用例
- python - 使用for循环将df数据插入sqlite
- c++ - 如果一个线程失败,我如何使用 std::barrier 让其他线程返回?