我的任务是创建符合我们的应用程序的自定义错误页面。我找到了https://wearestac.com/blog/dynamic-error-pages-in-rails,它工作得非常好。我没有得到任何路由错误,手动测试显示每个页面都正确呈现。
但是,在为用于将路由委托给视图的控制器创建控制器规范时,我遇到了一个问题。我的视图被命名为404.html.erb
,500.html.erb
,422.html.erb
。它们位于app/views
。我的代码与上面链接中列出的代码几乎完全相同,但为了便于后人和清楚起见,相关代码显示在下面,错误消息显示在下面:
错误消息:ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"errors", :params=>{:code=>"404"}}
应用程序/控制器/错误_控制器.rb:
# frozen_string_literal: true
class ErrorsController < ApplicationController
def show
render status_code.to_s, status: status_code
end
protected
# get status code from params, default 500 in cases where no error code
def status_code
params[:code] || 500
end
end
spec/controllers/errors_controller_spec.rb:
require 'rails_helper'
describe ErrorsController, type: :controller do
describe '#show' do
it 'renders the 404 error page when it receives a 404 status code' do
get :show, params: { code: '404' }
# ive also tried changing the param passed to redirect_to to error_404 to no effect
expect(response).to redirect_to(error_404_path)
end
it 'renders the 422 error page when it receives a 422 status code' do
get :show, params: { code: '422' }
expect(response).to redirect_to(error_422_path)
end
it 'renders the 500 error page when it receives a 500 status code' do
get :show, params: { code: '500' }
expect(response).to redirect_to(error_500_path)
end
end
end
config/routes.rb (只有相关的路由,完整的路由文件非常庞大)
%w(404 422 500).each do |code|
get code, to: "errors#show", code: code, as: 'error_' + code
end
config/application.rb (只有相关行,其他都是标准的):
config.exceptions_app = self.routes
我已经尝试扩展路由,以便显式定义每个路由,以及恢复到链接中的第一个非DRY形式。我还尝试将redirect_to
调用更改为render_template
调用,但没有效果。
我已经挠头好几天了,希望能弄明白这件事,但我一直没有运气。同样,路由在开发中工作得很好,但当我尝试在rspec中测试这些路由工作时,它找不到任何路由。
除了状态代码之外,文件中每个等级库的错误消息都是相同的。任何帮助都将不胜感激!
发布于 2017-03-30 15:15:47
尝试使用 :id参数来获取方法。Show action route需要:id参数(不带:id参数的show action的url实际上是索引操作url)。
get :show, params: { id: 1, code: '422' }
https://stackoverflow.com/questions/42306962
复制相似问题