在 rspec 中模拟错误/异常(不仅仅是它的类型) [英] mocking an error/exception in rspec (not just its type)
本文介绍了在 rspec 中模拟错误/异常(不仅仅是它的类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的代码块:
I have a block of code like this:
def some_method
begin
do_some_stuff
rescue WWW::Mechanize::ResponseCodeError => e
if e.response_code.to_i == 503
handle_the_situation
end
end
end
我想测试 if e.response_code.to_i == 503
部分发生了什么.我可以模拟 do_some_stuff 来抛出正确类型的异常:
I want to test what's going on in that if e.response_code.to_i == 503
section. I can mock do_some_stuff to throw the right type of exception:
whatever.should_receive(:do_some_stuff).and_raise(WWW::Mechanize::ResponseCodeError)
但是如何模拟错误对象本身在收到response_code"时返回 503?
but how do I mock the error object itself to return 503 when it receives "response_code"?
推荐答案
require 'mechanize'
class Foo
def some_method
begin
do_some_stuff
rescue WWW::Mechanize::ResponseCodeError => e
if e.response_code.to_i == 503
handle_the_situation
end
end
end
end
describe "Foo" do
it "should handle a 503 response" do
page = stub(:code=>503)
foo = Foo.new
foo.should_receive(:do_some_stuff).with(no_args)\
.and_raise(WWW::Mechanize::ResponseCodeError.new(page))
foo.should_receive(:handle_the_situation).with(no_args)
foo.some_method
end
end
这篇关于在 rspec 中模拟错误/异常(不仅仅是它的类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文