我已经编写了一个测试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页面。我想问题可能出在测试中我的“获取”操作格式错误,但我不确定。
编辑
config / 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”方法
答案 0 :(得分:0)
更改路线以使您的通话可以从浏览器进行:
get "/help/:id", to: "pages#help"
如果测试返回200
,那是因为它直接从您的控制器调用了help
方法,而没有使用config/routes.rb
文件。
编辑
以下是测试路由的方法:https://relishapp.com/rspec/rspec-rails/v/3-4/docs/routing-specs/route-to-matcher