在规范使用Rails默认异常翻译(Using Rails default exception tra

2019-10-18 11:03发布

我控制器抛出ActiveRecord::RecordNotFound这是可以预料的什么被翻译成404。

现在,我想在我的控制器规范来测试这种行为,但它得到例外,而不是response_code等于404如何使它得到这个代码呢?

Answer 1:

当Rails的养ActiveRecord::RecordNotFound它只是告诉你,ActiveRecord的是无法找到的资源在你的数据库(通常使用find )。

这是你的责任,以捕获异常,并做任何你想要做的(在你的情况下返回404未找到HTTP错误)。

一个简单的实现来说明以上是通过执行以下操作:

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  rescue_from ActiveRecord::RecordNotFound, with: :not_found

  private

  def not_found
    render file: 'public/404.html', status: 404, layout: false
  end
end

这样,每一次轨道将抛出ActiveRecord::RecordNotFound从继承任何控制器ApplicationController ,它将被救出并呈现位于404个轨默认页面public/404.html

现在,为了测试这一点:

spec/controllers/application_controller_spec.rb

require 'spec_helper'

describe ApplicationController do

  describe "ActiveRecord::RecordNotFound exception" do

    controller do
      def index
        raise ActiveRecord::RecordNotFound.new('')
      end
    end

    it "calls not_found private method" do
      expect(controller).to receive(:not_found)
      get :index
    end

  end

end

您将需要添加下面的在你的spec/spec_helper.rb

config.infer_base_class_for_anonymous_controllers = true


文章来源: Using Rails default exception translation in specs