使用 RSpec 进行存根睡眠 [英] Stub sleep with RSpec

查看:64
本文介绍了使用 RSpec 进行存根睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有以下代码:

I have the following code in my app:

def timeout_tasks
  10.times do
    # Work...
    sleep 2
  end
end

我想测试这个方法,但需要存根 sleep 以便我不必等待测试完成.

I would like to test this method, but need to stub sleep to I don't have to wait that much for the test to finish.

我该怎么做?我知道 allow(Object).to receive(:sleep) 但我不确定 Object 是什么.或者还有其他更好的方法吗?

How can I do this? I am aware of the allow(Object).to receive(:sleep) but I'm not sure what the Object is. Or is there any other better approach?

推荐答案

你应该在调用它的对象上存根 sleep

You should stub sleep on the object it is called on

例如

class SleepTest
  def sleep_method
    sleep 2
  end
end

在你的测试中

sleep_test = SleepTest.new
allow(sleep_test).to receive(:sleep)

这篇关于使用 RSpec 进行存根睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆