【问题标题】:RSpec Timecop failures around Date appear to be timezone related日期周围的 RSpec Timecop 故障似乎与时区有关
【发布时间】:2019-02-19 13:35:53
【问题描述】:

我们有一些测试(规范)在日期/时间附近失败。猜测这是一个 UTC 问题,但不确定为什么这些规范在上次项目被触及(约 8 个月前)时通过了!?!

#spec/features/cmets/creation_spec.rb

feature 'Comment creation', type: :feature, js: true do
  include CommentsPageHelpers
  ...
  let!(:current_date) { Date.parse('2017-01-03') }
  ...

  background do
    Timecop.freeze(current_date)
    ...
  end

  after do
    Timecop.return
  end

  shared_examples 'added comment' do |position:, text:|
    scenario 'adds single comment' do
        ...
        expect(page).to have_text 'January 3rd, 2017'
      end
    end
  end

视图(Angular 模板)#app/views/templates/comment.html.slim

.comment
  ...
  {{ comment.createdAt | moment: 'MMMM Do, YYYY' }}

#RSpec 失败

Comment creation for image behaves like added comment adds single comment
     Failure/Error: expect(page).to have_text 'January 3rd, 2017'
       expected to find text "January 3rd, 2017" in "John Snow First comment message January 2nd, 2017Remove"
     Shared Example Group: "added comment" called from ./spec/features/comments/creation_spec.rb:76
     # ./spec/features/comments/creation_spec.rb:42:in `block (4 levels) in <top (required)>'
     # ./spec/features/comments/creation_spec.rb:39:in `block (3 levels) in <top (required)>'

【问题讨论】:

  • 这是一个已知问题:github.com/travisjeffery/timecop/issues/100
  • hmm... 不能在一个 15 岁的框架中可靠地测试 Date 似乎很疯狂?!?解决方法?
  • 你真的不应该在 Rails 中使用 Date 因为它不是时区安全的。尝试Time.parse('2017-01-03').to_date 或票证中提到的其他解决方法。

标签: ruby-on-rails time rspec momentjs timecop


【解决方案1】:

let! 行更改为下面的两行似乎已经解决了问题。不知道它可能会破坏什么,或者它是否会破坏其他时区的开发人员?!?

Time.zone = 'Pacific Time (US & Canada)'
let!(:current_date) { Time.parse('2017-01-03').in_time_zone }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2011-12-09
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2016-05-09
    • 2013-06-14
    相关资源
    最近更新 更多