Ruby on rails 如何测试请求不返回500错误?
我正在尝试创建一个RSpec测试,它检测一个请求是否会使控制器崩溃,通常是一个500错误。因此,我希望能够区分:Ruby on rails 如何测试请求不返回500错误?,ruby-on-rails,ruby,rspec,rspec-rails,Ruby On Rails,Ruby,Rspec,Rspec Rails,我正在尝试创建一个RSpec测试,它检测一个请求是否会使控制器崩溃,通常是一个500错误。因此,我希望能够区分: nil.invalid_method # raises NoMethodError 从 以通用方式在控制器中。当我执行请求、功能或控制器测试时,会引发异常: describe "Post", type: :request do it 'does not crash when no params given' do post '/posts' # this line l
nil.invalid_method # raises NoMethodError
从
以通用方式在控制器中。当我执行请求
、功能
或控制器
测试时,会引发异常:
describe "Post", type: :request do
it 'does not crash when no params given' do
post '/posts' # this line launches an exception
expect(page).to_not have_http_status(500)
end
end
在RSpec(或我不知道的Rails)之前,似乎有一种不同的行为,类似于我正在寻找的:
谢谢您的时间。您可以使用不呈现500但引发异常的控制器规范:
describe "PostController", type: :controller do
describe "POST index" do
it 'does not crash with valid params' do
expect {
post :index, { post: { title: 'foo' } }
}.to_not raise_exception
end
end
describe "POST index" do
it 'crashes without params' do
expect {
post :index
}.to raise_exception(ActionController::ParameterMissing)
end
end
end
还要注意
expect
之后的花括号{…}
,您可以使用raise\u error
匹配器测试控制器是否未引发未捕获异常:
RSpec.describe "Things", type: :request do
describe "POST /things" do
it "does not raise an error" do
# we pass a block to expect
expect { post things_path }.to_not raise_error
end
end
end
如果在控制器中通过使用rescue
关键字或Railsrescue\u从
中救出异常,您将像往常一样测试响应代码:
class ThingsController < ApplicationController
rescue_from ActionController::ParameterMissing do
head 500
end
def create
raise ActionController::ParameterMissing.new('foo')
end
end
RSpec.describe "Things", type: :request do
describe "POST /things" do
it "work even if the param is not provided" do
post things_path
expect(response).to successful
end
end
end
类内容控制器
在这种情况下,更有用的是测试响应是否符合您的预期,而不是它不是500。@max@spickermann我没有正确解释自己。我的观点不是要检查引发了哪个异常。也许我的控制器正在以另一种方式处理这个问题,即:它在html中返回一条错误消息。因此,我需要一种通用的方法来检测是否存在“编码错误”。Rails使用异常来处理一些正确的情况,比如
ActionController::ParameterMissing
,因为除了{…}之外,我不能使用来不引发异常。
class ThingsController < ApplicationController
rescue_from ActionController::ParameterMissing do
head 500
end
def create
raise ActionController::ParameterMissing.new('foo')
end
end
RSpec.describe "Things", type: :request do
describe "POST /things" do
it "work even if the param is not provided" do
post things_path
expect(response).to successful
end
end
end