【问题标题】:UrlGenerationError in rspec testrspec 测试中的 UrlGenerationError
【发布时间】:2017-03-30 23:15:46
【问题描述】:

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

但是,在为用于将路由委托给视图的控制器创建控制器规范时,我遇到了问题。我的观点被命名为404.html.erb500.html.erb422.html.erb。它们位于app/views。我的代码与上面链接中列出的几乎完全相同,但是为了后代和清晰起见,相关代码如下所示,错误消息如下所示:

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

app/controllers/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

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 中是否有效时,它找不到任何路由。

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

【问题讨论】:

    标签: ruby-on-rails-4 rspec-rails rails-routing


    【解决方案1】:

    尝试添加 :id 参数 来获取方法。显示操作路由需要一个 :id 参数(没有 :id 参数的显示操作的 url 实际上是索引操作 url)。

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

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2015-01-13
      相关资源
      最近更新 更多