我试图在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
知道为什么会这样吗?
答案 0 :(得分:38)
答案 1 :(得分:2)
您始终可以使用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
答案 2 :(得分:1)
ActiveSupport
中的 travel_to
可能会更好地达到目的,并且可能如下所示:
def test_date
travel_to Time.zone.parse('1970-01-01')
verify
travel_back
end
答案 3 :(得分:1)
您可以使用timecop。冻结测试之前的时间,然后冻结之后的时间。
describe "some tests" do
before do
Timecop.freeze(Time.now)
end
after do
Timecop.return
end
it "should do something" do
end
end
或使用
定义特定时间let(:time_now) { Time.now }
并在Timecop.freeze(time_now)
和测试中使用