0

我正在尝试总结我写Timecopshared_example规范

describe "timecop wrapping shared example" do
   Timecop.freeze(1.day.ago) do
      it_behaves_like "a shared example i would like to test using timecop"
   end
end

shared_examples "a shared example i would like to test using timecop"
   before :all do
      puts "the current time is #{Time.now}"
   end

   ... expect ...
end

但是运行这个规范仍然使用实时而不是冻结的

Timecop可以这样工作吗?

我怎么能包装我的大块测试文件但改变它的运行时间

4

1 回答 1

2

Timecop 需要在 it 或 before 块内执行。

以下更改将解决您的问题。

describe "timecop wrapping shared example" do before { Timecop.freeze(1.day.ago) } it_behaves_like "a shared example i would like to test using timecop" end

Rspec 将在运行每个示例后重置环境(包括 Timecop)。

我在测试中发现了一些可能有用的时间旅行技巧:

  • Timecop.travel 更能反映您的代码在现实生活中的工作方式,因为时间永远不会静止。您可以像冻结一样使用它,只需将冻结方法换成旅行。

  • 如果你有 Rails 4.1 或更新版本,内置了很棒的时间旅行工具,你可以放弃你的 timecop gem。如果您想了解更多信息,请参阅博客文章文档。

于 2017-08-19T00:13:00.163 回答