使用 RSpec 对 Time.now 进行存根 [英] Stubbing Time.now with RSpec

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

问题描述

我正在尝试在 RSpec 中存根 Time.now,如下所示:

I am trying to stub Time.now in RSpec as follows:

it "should set the date to the current date" do
    @time_now = Time.now
    Time.stub!(:now).and_return(@time_now)

    @thing.capture_item("description")
    expect(@thing.items[0].date_captured).to eq(@time_now)
end

这样做时出现以下错误:

I am get the following error when doing so:

 Failure/Error: Time.stub!(:now).and_return(@time_now)
 NoMethodError:
   undefined method `stub!' for Time:Class

知道为什么会发生这种情况吗?

Any idea why this could be happening?

推荐答案

根据您的 RSpec 版本,您可能希望使用较新的语法:

Depending on your version of RSpec you might want to use the newer syntax:

allow(Time).to receive(:now).and_return(@time_now)

参见 RSpec Mocks 3.3

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

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