在规范中使用 Rails 默认异常转换 [英] Using Rails default exception translation in specs
问题描述
我的控制器正在抛出 ActiveRecord::RecordNotFound
,这是应该被翻译成 404 的内容.
My controller is throwing ActiveRecord::RecordNotFound
which is what to be expected to be translated into 404.
现在我想在我的控制器规范中测试这个行为,但它得到异常而不是 response_code
等于 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?
推荐答案
当 Rails 引发 ActiveRecord::RecordNotFound
时,它只是告诉您 ActiveRecord 无法在您的数据库中找到资源(通常是使用 find
).
When Rails raise a ActiveRecord::RecordNotFound
it simply telling you that ActiveRecord was not able to find a resource in your database (usually using find
).
您有责任捕捉异常并做您想做的任何事情(在您的情况下返回 404 not found http 错误).
It is your responsability to catch the exception and to do whatever you want to do (in your case return a 404 not found http error).
通过执行以下操作来说明上述内容的简单实现:
A simple implementation to illustrate the above is by doing the following:
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
,它将被拯救并呈现位于以下位置的 404 rails 默认页面public/404.html
This way every time rails will throw a ActiveRecord::RecordNotFound
from any controllers that inherit from ApplicationController
, it will be rescued and render the 404 rails default page located at 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
这篇关于在规范中使用 Rails 默认异常转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!