【问题标题】:Stubbing tomorrow's date in rspec在 rspec 中存根明天的日期
【发布时间】:2015-02-06 11:50:24
【问题描述】:

我有一个方法可以发送明天的日期(1.date.from_now)。我正在我的规范中测试相同的方法。谁能告诉我如何存根那个日期。

如果我通过 1.date.from 现在。出现以下错误。

   <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})

下面是我的方法

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

这是我的规格,

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

谁能告诉我如何解决这个问题

【问题讨论】:

标签: rspec-rails ruby-on-rails-4.1


【解决方案1】:

问题是时间可能看起来完全一样,但时间戳不是,运行两个语句之间花费的时间(即使是微秒)使时间不同,要解决它你应该在两个语句中使用相同的时间变量,例如:

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)

这样您可以确保两个语句中的时间相同,或者您可以使用像timecop 这样的 gem 来帮助您解决这个问题,就像 @gotva 建议的那样,timecop 非常有用,因为它让您能够冻结时间,及时向前和向后移动,这很好,对于你写这个的同一个例子

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

【讨论】:

    【解决方案2】:

    在我的方法中使用 Time.now + 1.day 解决。

    并存根 Time.now 并在传递参数时添加 1day 如下。

    current_time = Time.now
    Time.stub(:now) { current_time }
    S3Client.should_receive(:upload_csv_by_path).with("#{Rails.root}/tmp/scalar_test_exporter.csv", nil, expires: current_time + 1.day)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多