Rspec使用timecop包围shared_example

时间:2017-08-18 15:51:49

标签: ruby-on-rails rspec timecop

我试图将Timecop包裹在shared_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可以像这样工作吗?

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

1 个答案:

答案 0 :(得分:2)

Timecop需要在它内部或之前执行。

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

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宝石。如果您想了解更多信息,请参阅blog postthe docs

相关问题