2017-08-18 21 views
0

我试图总结Timecop围绕shared_example规范我写Rspec的周围有时空特警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 

但运行该规范仍然使用真实的时间,而不是冻结的一个

可以时空特警这样工作?

我还能怎么包装大块我的测试文件,但改变它在运行

回答

1

时空特警需要在它内部或块之前执行的时间。

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

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.travel更反映出大家对你的代码会在现实生活中工作,随着时间永远保持静止。您可以像冻结一样使用它,只需将冻结方法换出即可。

  • 如果您有Rails 4.1或更新版本,那么您可以使用内置的优质时间旅行工具,并且可以放弃时间点宝石。如果您想了解更多信息,请点击blog postthe docs

+0

我希望它在一个块中运行,因为如果我的shared_example使用以及Timecop.freeze(和它),当它Timecop.return,它会回到我原来的“真实”的时间,而不是冻结了共享示例的时间。 – amitben

+0

rspec是不是在清理你的环境之间的例子?如果不是,你的rspec设置可能有问题。另一种选择是使用[around而不是之前](https://relishapp.com/rspec/rspec-core/v/2-0/docs/hooks/around-hooks) – Teresa

+0

shared_example调用将“重置”时间返回到当前时间。如果我会在描述的“timecop包装共享示例”中写入共享示例,那么它一切正常 – amitben