我想测试一些截止日期是否在不同时区和一天中的不同时间正确地显示给用户。我的测试使用 capybara+rspec+phantomjs。
我将一个块传递给 Timecop.travel(datetime) 并且该块内的测试代码正确地获取了模拟的日期时间,但看起来 PhantomJS / 模拟的浏览器没有得到模拟的时间。
有什么已知的方法可以让 PhantomJS 与 Timecop 一起工作吗?或者其他方式来模拟或操纵时间以进行测试?
这是一个简单的例子来说明我的意思。
time_spec.rb:
it "should show the Time travel date" do
# current date is 2017-01-24
Date.today.should == Date.parse("2017-01-24")
Timecop.travel( Time.parse("2001-01-01 01:01") ) {
sign_in(user)
visit "/#{user.username}"
Date.today.should == Date.parse("2001-01-01")
page.should have_text("Today is 2001-01-01")
page.should have_text("Javascript says 2001-01-01")
}
end
用户.html.erb:
<p>Today is <%= Time.now.iso8601 %></p>
<script>
var now = moment().format()
$('p').append("<p>Javascript says "+now+"</p>")
</script>
运行测试的输出:
Failures:
1) Dashboard should show the time travel date
Failure/Error: page.should have_text("Javascript says 2001-01-01")
expected to find text "Javascript says 2001-01-01" in
"Today is 2001-01-01T01:01:00-08:00 Javascript says 2017-01-24T12:36:02-08:00"
# ./spec/features/time_spec.rb:67:in `block (3 levels) in <top (required)>'
# /gems/ruby-2.2.0/gems/timecop-0.8.0/lib/timecop/timecop.rb:147:in `travel'
# /gems/ruby-2.2.0/gems/timecop-0.8.0/lib/timecop/timecop.rb:121:in `send_travel'
# /gems/ruby-2.2.0/gems/timecop-0.8.0/lib/timecop/timecop.rb:62:in `travel'
# ./spec/features/time_spec.rb:59:in `block (2 levels) in <top (required)>'