gpt4 book ai didi

ruby-on-rails - 模拟 rspec 中的错误/异常(不仅仅是它的类型)

转载 作者:数据小太阳 更新时间:2023-10-29 06:39:05 24 4
gpt4 key购买 nike

我有一段代码是这样的:

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 以抛出正确类型的异常:

whatever.should_receive(:do_some_stuff).and_raise(WWW::Mechanize::ResponseCodeError)

但是我如何模拟错误对象本身以在收到“response_code”时返回 503?

最佳答案

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

关于ruby-on-rails - 模拟 rspec 中的错误/异常(不仅仅是它的类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2067801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com