WebMock模拟失败的API(没有互联网,超时++)
我试图使用webmock模拟来自web api的意外行为,例如找不到服务器和超时。
最好的方法是什么? 我能想到的就是做这样的事情:
stubbed_request = stub_request(:get, "#{host}/api/something.json"). with(:headers => {'Accept'=>'*/*', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}). to_return(:status => [500, "Internal Server Error"])
这应该适用于像404等,但如何测试超时 , 服务器未找到/脱机服务器 , 没有互联网连接 ?
经过一番挖掘后,我找到了一些解决方案。
显然你可以将to_return(...)
更改为to_timeout
,这将引发超时错误。 您还可以使用to_raise(StandardError)
。 有关完整参考,请参阅https://github.com/bblimke/webmock#raising-timeout-errors 。
超时或未找到服务器 ,例如:
stubbed_request = stub_request(:get, "#{host}/api/something.json"). with(:headers => {'Accept'=>'*/*', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}). to_timeout
引发StandardError,或者没有互联网 /其他exception,例如:
stubbed_request = stub_request(:get, "#{host}/api/something.json"). with(:headers => {'Accept'=>'*/*', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}). to_raise(StandardError) #Error example 2: stubbed_request = stub_request(:get, "#{host}/api/something.json"). with(:headers => {'Accept'=>'*/*', 'Content-Type'=>'application/json', 'User-Agent'=>'Ruby'}). to_raise("My special error")
你走了,毕竟不是太难。
我不知道我是怎么第一次没找到这个。 无论如何,希望有一天能帮到某人。