gpt4 book ai didi

ruby - 如何测试 (rspec) 花费太长时间的 http 请求?

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:17 25 4
gpt4 key购买 nike

如果使用 rspec 请求花费的时间太长,我该如何测试行为?

我正在考虑使用线程来模拟这个:

describe "Test" do 
it "should timeout if the request takes too long" do
lambda {
thread1 = Thread.new { #net::http request to google.com }
thread2 = Thread.new { sleep(xx seconds) }
thread1.join
thread2.join
}.should raise_error
end
end

我想确保在第一次发出请求后,另一个线程“启动”,在这种情况下只是休眠 xx 秒。然后我应该期望请求超时,因为执行时间太长

我认为有更好的方法可以做到这一点。鉴于我请求的网址不相关。我只是想测试一下,如果执行时间过长,确实会超时。

我可以使用 stub()、expect() 或任何 rspec 功能来模拟吗?

有什么方法可以将“ block ”传递给 stub 方法

http_request_to_google.stub(:connection).executethisblock(sleep for xx seconds)
.and_throw error ?

感谢任何帮助

最佳答案

如果请求未在 20 秒内完成,则以下测试失败。如果 lambda 中的代码没有引发 Timeout::Error,它也会失败。

因此,成功的场景是 long_running_stuff 在不到 20 秒内引发异常。

require 'timeout'

describe "Test" do
it "should timeout if the request takes too long" do
Timeout::timeout(20) do # 20 seconds
lambda {
long_running_stuff(:timeout => 10.seconds)
}.should raise_error(Timeout::Error)
end
end
end

关于ruby - 如何测试 (rspec) 花费太长时间的 http 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9008442/

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