【问题标题】:(Rails) Test fails during late night time(Rails) 深夜测试失败
【发布时间】:2015-11-13 16:16:30
【问题描述】:

我的 rails 应用程序包含许多测试。所有测试都在常规情况下通过。也就是说,不包括深夜。

实际上有一些测试在晚上结束时会失败。所有这些测试都涉及修改模型的时间属性并查看相关模型是否受到影响。

test "changing time should affect hours" do
    // ..User is loaded.
    user.attend(event)
    assert_equal 1, user.hours // User attends a 1 hour event that has passed. 
    // Move event to the future.
    event.update_attributes(date: Date.today,
                              start_time: Time.now,
                              end_time: Time.now + 1.hour)
    assert_equal 0, attendance_of(user).hours // Passes in day, fails during night
  end

test "valid event creation" do
    // Count does NOT change by 1 at night.
    assert_difference '@group.events.count', 1 do
      post group_events_path(@group), event: { ...
                                                date: Date.today,
                                                start_time: Time.now,
                                                end_time: Time.now + 1.hour,
                                                ... }
    end
  end

这里发生了什么?作为参考,这是我目前用来确定何时更新 attendance 的内容(这是 event 所具有的)。这来自事件控制器:

  def not_ended?
    date.future? || (date.today? &&
      (Time.now.seconds_since_midnight < end_time.seconds_since_midnight))
  end

  def update_attendances
    // ... Determine the new date, start, and end time values through ActiveRecord::Dirty
    if not_ended?
      remove_checks = true
    end
    attendances.each do |attendance|
      new_checked = remove_checks ? false : attendance.checked
      attendance.update_attributes(went: new_start, left: new_end,
                                    checked: new_checked)
    end
  end
end

验证事件以确保其时间不奇怪:

    def valid_time
      if start_time == end_time
        // Error...
      end
      if start_time > end_time
        // Error...
      end
    end

application.rb 中的时区:

config.time_zone = 'Pacific Time (US & Canada)'

【问题讨论】:

  • 一个词:时区。我还没有看到错误,但肯定是他们。
  • 你在哪里运行这些测试?本地或某些 CI 服务(信号量、travis)?
  • 是的!时区 :-) 我们也有一些类似的测试!
  • 另外,UTC 中的“深夜时间”到底是什么?
  • 不一定是时区。对我来说,当事件进入第二天系统认为它实际上已经过去时,这看起来像是一个边界错误。

标签: ruby-on-rails testing time relationship


【解决方案1】:

使用 Time.zone.now 或 timecop.freeze 冻结时区,因为您的测试可能使用系统时间而不是 rails 应用配置时间

【讨论】:

    【解决方案2】:

    您的not_ended? 方法已损坏。当事件在午夜之前开始,但在之后结束时,它不起作用。在这种情况下,日期为今天(假设数据基于开始时间),但距事件结束午夜的秒数小于当前时间。

    在这些情况下,您不应该尝试分别处理日期和时间。您应该有办法检索事件结束的日期时间并将其与当前日期时间进行比较。

    【讨论】:

    • 可能就是这样。但是,我需要一个很好的方法来获取事件的日期时间。事件的 datedate,而它的 start_timeend_time 属性是 times。试图弄清楚这一点。
    • 事实证明我的模型不是为多日活动设置的。
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多