【发布时间】:2013-08-04 18:31:32
【问题描述】:
我的控制器正在抛出 ActiveRecord::RecordNotFound,这是预期会被翻译成 404 的内容。
现在我想在我的控制器规范中测试此行为,但它得到异常而不是等于 404 的 response_code。如何让它获取此代码?
【问题讨论】:
标签: ruby-on-rails-3.2 rspec2 rspec-rails
我的控制器正在抛出 ActiveRecord::RecordNotFound,这是预期会被翻译成 404 的内容。
现在我想在我的控制器规范中测试此行为,但它得到异常而不是等于 404 的 response_code。如何让它获取此代码?
【问题讨论】:
标签: ruby-on-rails-3.2 rspec2 rspec-rails
当 Rails 提出 ActiveRecord::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 会从任何继承自 ApplicationController 的控制器抛出一个 ActiveRecord::RecordNotFound,它将被拯救并呈现位于 public/404.html 的 404 rails 默认页面
现在,为了测试这个:
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
【讨论】: