2017-02-17 42 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' }