Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing Time.now with RSpec

Tags:

ruby

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?

like image 641
Patrick Kayongo Avatar asked Aug 30 '15 19:08

Patrick Kayongo


2 Answers

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

like image 151
spickermann Avatar answered Nov 10 '22 18:11

spickermann


travel_to from ActiveSupport might serve the purpose better and might look as follows:

def test_date
  travel_to Time.zone.parse('1970-01-01')
  verify
  travel_back
end
like image 10
Artur Beljajev Avatar answered Nov 10 '22 17:11

Artur Beljajev