5

注意:根据 RafaeldeF.Ferreira 的建议,这个问题自其原始形式以来已被大量编辑。

我的基于 JSON 的应用程序需要在给出错误路由时返回一些合理的东西。我们已经知道以下内容rescue_from ActionController::RoutingError在 Rails 3.1 和 3.2 中不起作用:

# file: app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery
  rescue_from ActionController::RoutingError, :with => :not_found
  ...
end

(这在https://github.com/rails/rails/issues/671中有详细记录。)因此,我实现了 José Valim 在此博客条目(第 3 项)中描述的内容,详细信息如下所示。

但是测试它一直存在问题。此控制器 rspec 测试:

# file: spec/controllers/errors_controller.rb
require 'spec_helper'
require 'status_codes'
describe ErrorsController do
  it "returns not_found status" do
    get :not_found
    response.should be(StatusCodes::NOT_FOUND)
  end
end

失败:

ActionController::RoutingError: No route matches {:format=>"json", :controller=>"sites", :action=>"update"}

然而这个集成测试调用 ErrorsController#not_found 并成功:

# file: spec/requests/errors_spec.rb
require 'spec_helper'
require 'status_codes'

describe 'errors service' do
  before(:each) do
    @client = FactoryGirl.create(:client)
  end

  it "should catch routing error and return not_found" do
    get "/v1/clients/login.json?id=#{@client.handle}&password=#{@client.password}"
    response.status.should be(StatusCodes::OK)
    post "/v1/sites/impossiblepaththatdoesnotexist"
    response.status.should be(StatusCodes::NOT_FOUND)
  end
end

那么:有没有办法使用普通控制器测试来测试“捕获所有路线”?

实施细节

如果您想查看实现,这里是相关的代码片段

# config/routes.rb
MyApp::Application.routes.draw do
  ... all other routes above here.
  root :to => "pages#home"
  match "/404", :to => "errors#not_found"
end

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.exceptions_app = self.routes
    ...
  end
end

# config/environments/test.rb
MyApp::Application.configure do
  ...
  config.consider_all_requests_local       = false
  ...
end

# app/controllers/errors_controller.rb
class ErrorsController < ApplicationController
  def not_found
    render :json => {:errors => ["Resource not found"]}, :status => :not_found
  end
end
4

0 回答 0