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

标签 ruby rspec bdd

如果使用 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/

相关文章:

ruby-on-rails - Rails : "private method ` require' called for #<Hash. .."手动创建记录时(不是通过表单)

ruby-on-rails - RSpec:验证器的共享示例?

Rails 4升级后mysql错误

jquery - 如何触发 keyup 事件并传递 key ?

testing - 您的 BDD 规范应该与 UI 测试分开吗?

unit-testing - 测试后端 api 端点是否被视为单元测试?

ruby - 如何为包含 "gets.chomp"的 Ruby 方法编写 RSpec 测试?

ruby - 抓取目录中具有特定扩展名的所有文件,而不管扩展名大小写(不区分大小写的扩展名)Ruby

ruby - 为什么 Heroku 的 heroku-18 堆栈仅与 Puma 版本 3.7.x 兼容?

rspec - 在 View 规范之间共享代码