Search code examples
rspec-railsruby-on-rails-4.1

Stubbing tomorrow's date in rspec


I have a method in which am sending tomorrow's date(1.date.from_now). I'm testing the same method in my specs. Can anyone tell me how to stub that date.

if I pass 1.date.from now. am getting following error.

   <S3Client (class)> received :upload_csv_by_path with unexpected arguments
     expected: ("/home/projects/sh/tmp/test_exporter.csv", nil, {:expires=>Sat, 07 Feb 2015 11:36:39 UTC +00:00})
          got: ("/home/projects/sh/tmp/test_exporter.csv", nil, {:expires=>Sat, 07 Feb 2015 11:36:39 UTC +00:00})

below is my method

S3Client.upload_csv_by_path(file_name, nil, expires: 1.day.from_now)

Here is my spec,

S3Client.should_receive(:upload_csv_by_path).with("#{Rails.root}/tmp/scalar_test_exporter.csv", nil, expires: 1.day.from_now)

Can anyone tell me how can i solve this issue


Solution

  • The issue is that the times might look exactly the same, but the timestamps aren't, the time which is spent between running the two statements ( even if it's in micro seconds ) makes the time different, to solve it you should use the same time variable in both statements, for example:

    time = Time.now
    S3Client.should_receive(:upload_csv_by_path).with("#{Rails.root}/tmp/scalar_test_exporter.csv", nil, expires: time)
    S3Client.upload_csv_by_path(file_name, nil, expires: time)
    

    This way you could make sure that the time is the same in both statements, or you could use a gem like timecop to help you with this like @gotva suggested, timecop is very useful because it gives you the ability to freeze time, move forward and backwards in time, it's nice, for the same example you'd write this

    Time.freeze
    S3Client.should_receive(:upload_csv_by_path).with("#{Rails.root}/tmp/scalar_test_exporter.csv", nil, expires: 1.day.from_now)
    S3Client.upload_csv_by_path(file_name, nil, expires: 1.day.from_now)
    Time.return