2017-02-17 71 views
0

我的任务是创建与我们的应用程序一致的自定义错误页面。我发现https://wearestac.com/blog/dynamic-error-pages-in-rails它工作得很好。我没有得到任何路由错误,并且手动测试显示每个页面都正确显示。rspec测试中的UrlGenerationError

但是,当为控制器创建控制器规格用于将路由委托给视图时,我遇到了一个问题。我的意见被命名为404.html.erb500.html.erb,422.html.erb。他们位于app/views。我的代码几乎是完全一样的东西在上面的链接中列出,但对子孙后代和清晰,相关的代码如下所示以及如下错误信息:

错误消息:ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"errors", :params=>{:code=>"404"}}

应用程序/控制器/ errors_controller.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 

规格/控制器/ 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 

配置/路由s.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中工作时,它找不到任何路由。

除状态码外,错误消息对于文件中的每个规格都是相同的。任何帮助,将不胜感激!

回答

0

尝试add:id param获取方法。显示动作路线期待一个:ID参数(没有显示动作的URL:ID参数实际上是索引动作URL)。

get :show, params: { id: 1, code: '422' }