1

My controller is throwing ActiveRecord::RecordNotFound which is what to be expected to be translated into 404.

Now I want to test this behaviour in my controller spec, but it gets exception rather than response_code equal to 404. How to make it get this code instead?

4

1 回答 1

2

当 Rails 提出 aActiveRecord::RecordNotFound时,它只是告诉您 ActiveRecord 无法在您的数据库中找到资源(通常使用find)。

您有责任捕获异常并执行您想做的任何事情(在您的情况下返回 404 not found 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

这样,每次 rails 会ActiveRecord::RecordNotFound从任何继承自的控制器抛出 a 时ApplicationController,它都会被救出并呈现位于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
于 2013-08-03T16:25:02.543 回答