You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级依赖Date gem 3.3.3后日期断言失败求助

问题原因及解决方案

这个问题根源在于Date gem 3.3.x版本对DateTime的时区处理逻辑做了变更,导致原本能通过的跨类型(ActiveSupport::TimeWithZone vs DateTime)相等断言失效。

具体原因

  • 你的断言左边是ActiveSupport::TimeWithZone对象,右边是to_datetime生成的DateTime对象。在旧版Date gem中,这两种类型的UTC时间比较会被隐式兼容,认为相等。
  • Date gem 3.3.0+调整了DateTime的时区内部表示,尤其是UTC时区的处理逻辑,使得DateTime和ActiveSupport::TimeWithZone的==比较不再返回true,即使它们代表的时间点完全一致。

修复方案

你需要统一两边的类型来修复断言:

  • 方案1:把右边转换成ActiveSupport::TimeWithZone
    expect(order.purchased_at).to eq Time.zone.parse('Sun, 26 Jan 0020 00:00:00 UTC +00:00')
    # 或者
    expect(order.purchased_at).to eq 'Sun, 26 Jan 0020 00:00:00 UTC +00:00'.to_datetime.in_time_zone
    
  • 方案2:把左边转换成DateTime
    expect(order.purchased_at.to_datetime).to eq 'Sun, 26 Jan 0020 00:00:00 UTC +00:00'.to_datetime
    

如果是测试精确时间,推荐方案1,因为Time.zone.parse会直接生成和order.purchased_at同类型的对象,避免跨类型比较的潜在问题。

内容的提问来源于stack exchange,提问作者svelandiag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:02:40