rubyrspec

Stubbing Time.now with RSpec


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?


Solution

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

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

    See RSpec Mocks 3.3