为Timeout::Error和 Errno::ECONNREFUSED编写测试用例
下面的测试:
assert_raises(Timeout::Error) do
Timeout.timeout(1) do
sleep(5) # This should exceed the timeout
post confirm_execution_url, params: { txdoc_id: this_txdoc.id }, "headers": { "host": "www.example.com" }
end
end
似乎并未落入控制器动作的rescue块中
begin
@result = HTTParty.post( 'https://www.example.co/ae/api.php', {
body: data_block,
headers: {'Content-Type' => 'application/json'}
})
rescue Timeout::Error, Errno::ECONNREFUSED, SocketError => e
binding.break
unsent_doc( doc, 'timeout_error', 'job' )
flash[:alert] = "API connection failed. Retrying in background..."
end
因为break没有被执行。
我怀疑涉及桩(stub),但——因为桩会模仿一个连接——我实在想象不出一个桩到底如何能够真正模拟出“断开连接”的情景。
这个测试应该如何编写?
解决方案
每个条件都可以通过一个桩(stub)来测试
stub_request(:post, "https://www.example.co/ae/api.php").
to_raise(Errno::ECONNREFUSED)
并且
stub_request(:post, "https://www.example.co/ae/api.php").
to_timeout
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。