Stpecbing Time.now与RSpec
我试图在RSpec中将Time.now存根如下:
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
这样做时我收到以下错误:
Failure/Error: Time.stub!(:now).and_return(@time_now) NoMethodError: undefined method `stub!' for Time:Class
知道为什么会这样吗?
根据您的RSpec版本,您可能希望使用较新的语法:
allow(Time).to receive(:now).and_return(@time_now)
见RSpec Mocks 3.3
你总是可以使用timecop :
@time_now = Time.now Timecop.freeze(@time_now) do @thing.capture_item("description") expect(@thing.items[0].date_captured).to eq(@time_now) end
来自ActiveSupport
travel_to
可能会更好地ActiveSupport
作用。 伪代码:
def test_date travel_to Time.zone.parse('1970-01-01') verify travel_back end