如何在 Sinatra 上使用rack/test 测试处理异常的操作?
我想测试我在 Sinatra 上制作的这条路线:
get '/party' do
begin
party_source.parties
rescue Exceptions::SourceNotFoundError
status 404
rescue Exceptions::SourceInternalError
status 503
end
end
我编写了这个测试(假设测试可以访问 party_source,在实际代码中它是):
require 'rack/test'
def test_correct_status_code_when_get_error_404
source_404 = mock()
source_404.expects(:parties).with(nil).raises(Exceptions::SourceNotFoundError)
MyApp.party_source = source_404
get '/party'
assert_equal 404, last_response.status
end
当我运行这个测试时,它失败了,因为它没有得到 404 (我的代码)我得到状态 500。无论我提出什么异常,我总是得到状态 500,我认为这是由 Sinatra 或 Rack 生成的。
我该如何测试这个案例?
更新
据我所知,异常没有被我的救援块捕获。 Rack 或 Sinatra 正在获取它并处理 HTTP Status 500 响应消息。
我不明白我的救援代码块是如何被忽略的。
I want to test this route I made on Sinatra:
get '/party' do
begin
party_source.parties
rescue Exceptions::SourceNotFoundError
status 404
rescue Exceptions::SourceInternalError
status 503
end
end
And I wrote this test (assume the party_source is accessible by the test, in the actual code it is):
require 'rack/test'
def test_correct_status_code_when_get_error_404
source_404 = mock()
source_404.expects(:parties).with(nil).raises(Exceptions::SourceNotFoundError)
MyApp.party_source = source_404
get '/party'
assert_equal 404, last_response.status
end
When I run this test it fails because instead of getting 404 (my code) I get a status 500. No matter what exception I raise I always get and status 500, which I think is being generated by Sinatra or Rack.
How can I test this case?
Update
As I can understand it, the exceptions isn't getting caught by my rescues blocks. Rack or Sinatra is getting it and handling the HTTP Status 500 response message.
I can't understand how my rescue code block is being ignored.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
下面是一个简短的示例,显示您可以测试这样的操作:
hello_sinatra.rb
:sinatra_test.rb
:但是,您的代码中有些东西看起来很奇怪。您可以尝试将
MyApp.party_source = source_404
替换为app.party_source = source_404
更新
您只捕获
Exceptions::SourceNotFoundError
和Exceptions::SourceInternalError
,您的模拟中可能出现其他问题,从而出现 500 错误。使用
rescue Exception
在开始/救援块的末尾添加一个包罗万象的内容,您将很快看到问题出在哪里。Here's a short example, showing that you can test such an action:
hello_sinatra.rb
:sinatra_test.rb
:However, something looks strange in your code. Can you try to replace
MyApp.party_source = source_404
withapp.party_source = source_404
Update
You're only catching
Exceptions::SourceNotFoundError
andExceptions::SourceInternalError
, something else is likely going wrong in your mock, which gives the 500 error.Add a catchall at the end of your begin/rescue block using
rescue Exception
and you will quickly see where the problem is.