0

我有这个错误控制器:

class ErrorsController < ApplicationController
  def error_404
    @not_found_path = params[:not_found]
    @return_page = request.referer || root_path
    errors_respond 404
  end

  def error_500
    errors_respond 500
  end
end

在我的applicaiton_controller.rb我有

def render_error(status, exception)
  errors_respond status
rescue
end

render_error 方法在application_helper.rb-file中定义

def errors_respond(status)
  respond_to do |format|
    format.html { render :template => "errors/error_#{status}", :layout => 'layouts/application_bootstrap', :status => status }
    format.all { render :nothing => true, :status => status }
  end
end

routes.rb在我的-file的最底部,我有

match '/i_really_do_not_exist', to: redirect('/') # WTF? error_controller_specs will fail if this is removed
match '*not_found', to: 'errors#error_404'

提到error_controller_spec.rb的是这个

require 'spec_helper'

describe ErrorsController do
  describe "GET 'error_404'" do
    it "returns http status 404" do
      get 'error_404'
      response.response_code.should == 404
    end
  end

  describe "GET 'error_500'" do
    it "returns http status 500" do
      get 'error_500'
      response.response_code.should == 500
    end
  end
end

如果我在没有'/i_really_do_not_exist'路径的情况下运行它们,它们会失败

ActionController::RoutingError:
No route matches {:controller=>"errors", :action=>"error_404"}

如果我删除了/.

我可以更改匹配部分和重定向部分,并且我的规范将通过,但是如果我完全删除它,它们会失败。

生成的路由match '/i_really_do_not_exist' => redirect('/'):controller#:action.

有谁知道怎么回事?

4

1 回答 1

0

我有一个理论。

您可能实际上没有通往错误#error_404 的路线。当 rspec 尝试访问它时,此行:

match '/i_really_do_not_exist' => redirect('/')

将其重定向到错误控制器和操作。如果没有该行,则会发生 RoutingError,因为没有路由。

检查的输出rake routes以查看是否存在到 errors#error_404 的路由。如果没有,请检查您的路线文件和文件名。很容易错误地命名文件error_controller.rb而不是errors_controller.rb.

编辑:

我想当你这样做的时候

get 'error_404'

errors_controller_specRSpec 中尝试 GET /errors_controller/error_404,这不在您的路线中。当然,您实际上并不希望任何人访问该 URL,因此在您的路线中不要包含它是正确的。我认为你应该做的是有一个规范来反映预期的行为:即当有人试图访问不存在的东西时路由到 errors#error_404 。您可能希望在不同的规范文件中执行此操作,因为它描述了一般行为。看:

https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller

于 2013-10-11T16:45:03.690 回答