2013-10-11 44 views
0

我有这种错误的控制器:怪异情况下与路线和error_controller

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的最底部 - 文件我有

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

任何人都知道发生了什么事?

+1

您是否尝试过用与不用这些线路比较'''耙routes'''输出? – jcm

+0

我编辑了问题以包含'/ i_really_do_not_exist'的路由,它是':controller#:action'。 –

回答

0

我有一个理论。

您可能实际上没有找到错误#error_404的路线。当rspec试图访问它时,该行:

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

将其重定向到错误控制器和操作。没有这条线,就会发生RoutingError,因为没有路由。

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

编辑:

我认为当你在做errors_controller_spec

get 'error_404' 

RSpec的试图让/errors_controller/error_404,这是不是在你的路由。当然,你实际上并不希望任何人访问该URL,因此不要在你的路由中使用它。 我认为你应该做的是有一个规范反映预期的行为:即当有人试图访问一些不存在的东西时,路由到错误#error_404。您可能希望在不同的spec文件中执行此操作,因为它描述了一般行为。请参阅:

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

+0

我确实有一条路线到'error_404'。运行'rake routes'时出现:'/*not_found(.:format)errors#error_404'。 –

+0

@MadsOhmLarsen是的但RSpec不知道这一点。看到我编辑的答案。 – jcm