导轨上的红宝石 - 使用 rspec 自定义 404 错误路由



只是偶然发现了这个并在写问题时找到了答案 - 因为这是一个常见的用例,我想我会分享它。直到一分钟前,我还遇到了以下问题:

我已经使用带有以下代码的错误控制器为我的 rails 应用程序设置了一个自定义 404 页面:

def index
    render "errors/index", status: 404
end

我已经将我的路由设置为在访问不存在的路由时呈现此 404 页面:

devise_for :users
get "errors/index", as: :error
get "*not_found", to: "errors#index" # this is the important line
root to: "welcome#index"

事实上,它确实有效。但是,由于某种原因,我的规范不起作用:

it "renders 404 on unknown route" do
    get("/thisrouteiswrong").should route_to("errors#index")
end

终端中生成的输出为:

The recognized options <{"controller"=>"errors", "action"=>"index", "not_found"=>"thisrouteiswrong"}> did not match <{"controller"=>"errors", "action"=>"index"}>, difference: <{"not_found"=>"thisrouteiswrong"}>.
   <{"controller"=>"errors", "action"=>"index"}> expected but was
   <{"controller"=>"errors", "action"=>"index", "not_found"=>"thisrouteiswrong"}>.

如终端的错误所示,请求还有一个名为not_found的参数,该参数是通过路由设置的。我所要做的就是像这样将该参数传递到测试中:

it "renders 404 on unknown route" do
    get("/thisrouteiswrong").should route_to("errors#index", "not_found" => "thisrouteiswrong")
end

最新更新