Home > front end >  Stubbing Time.zone.now in RSpec returns blank when called
Stubbing Time.zone.now in RSpec returns blank when called

Time:12-27

I tried stubbing Time.zone.now and it seems to work up until it is called when storing the timestamp in an ActiveRecord field

In my RSpec file, I stub the method Time.zone.now as such:

current_time = Time.zone.now
zone_ = double(zone_)

allow(Time).to receive(:zone).and_return(zone_)
allow(zone_).to receive(:now).and_return(current_time)

When I call binding.pry after stubbing and check Time.zone.now I get a valid timestamp all the way up until it is called in the method I am testing. For some reason, it is blank. I use the timestamp to save it to a field in an ActiveRecord object I am creating. So, I get this error:

ActiveRecord::RecordInvalid:
       Validation failed: <My_Field> can't be blank

What is the best way to stub Time.zone.now?

CodePudding user response:

Just to wrap up the comments: the best way to stub Time in Rspec is not to do it manually.

You can use the Timecop Gem.

  • Related