ruby-on-rails - 如何控制 capybara /phantomjs 测试的时间

标签 ruby-on-rails testing phantomjs capybara timecop

我想测试一些截止日期是否在不同时区和一天中的不同时间正确地显示给用户。我的测试使用的是 capybara+rspec+phantomjs。

我正在将一个 block 传递给 Timecop.travel(datetime),并且该 block 中测试中的代码正确地获取了模拟的日期时间,但看起来 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

user.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)>'

最佳答案

正如您所发现的,TimeCop 仅调整服务器时间,但浏览器使用系统时间。有许多 JS 库允许时间伪造,它们都通过模拟 JS 日期类来工作。我成功使用的一个是 Sinon.JS这是我在我的 _head.html.haml 文件中实现的

- if defined?(Timecop) && Timecop.top_stack_item
  = javascript_include_tag "testing/sinon-1.17.3.js"
  - unix_millis = (Time.now.to_f * 1000.0).to_i
  :javascript
    sinon.useFakeTimers(#{unix_millis});

在要求任何其他 JS 之前。这会将呈现的任何页面中的浏览器时间设置为 Timecop 设置的值。

关于ruby-on-rails - 如何控制 capybara /phantomjs 测试的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41838864/

相关文章:

ruby-on-rails - 如何进行 Rails 外部数据库调用?

Android IAB 测试 : app in draft state but in alpha slot, 无法检索 Activity 产品

facebook - 如何为应用程序页面创建测试用户?

c# - 无法从 PhantomJS 中的本地文件加载 html

javascript - 使用 PhantomJS 和 node.js 保存和渲染网页

ruby-on-rails - Rails 应用程序.html.erb?

ruby-on-rails - Rails 5 - 找不到生成器 'rspec:install'

testing - @RunWith(Cucumber.class) 和@Autowired MockMvc

javascript - 在 PhantomJS 2 中运行测试时从 Karma 截取屏幕截图?

mysql - 在 ROR 迁移期间将列类型从 Date 更改为 DateTime