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

升级Rails 6.1后PostgreSQL时间戳出现额外精度值致测试失败

Rails 6.1升级后PostgreSQL Timestamp字段精度导致测试失败的解决办法

问题根源

Rails 6.1对PostgreSQL的timestamp类型处理做了关键变更:默认会读取并返回数据库存储的完整时间精度(微秒级别),而Rails 6.0及更早版本会自动将timestamp字段截断到秒级输出。这种差异直接导致测试用例里的时间断言全部失败。

可行解决方法

1. 全局恢复6.0的秒级截断行为

如果想让整个应用的timestamp字段都回到6.0的表现,可以在配置文件中添加全局设置:

  • 在config/initializers/new_framework_defaults_6_1.rb中添加:
# 全局禁用timestamp微秒精度,统一截断到秒
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.datetime_precision = 0
  • 或者在config/database.yml的默认配置里添加变量:
default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  # 新增以下配置,强制datetime精度为0(秒级)
  variables:
    datetime_precision: 0

2. 针对特定模型字段单独配置

如果只需要调整部分字段的精度,直接在对应模型中指定:

class User < ApplicationRecord
  # 对created_at、updated_at以及自定义的start_date字段设置秒级精度
  attribute :created_at, :datetime, precision: 0
  attribute :updated_at, :datetime, precision: 0
  attribute :start_date, :datetime, precision: 0
end

3. 调整测试用例适配微秒精度

如果希望保留Rails 6.1的精度特性,只需修改测试断言,允许时间的微秒级误差:

# 原测试(会失败):
expect(user.created_at).to eq(Time.parse("2015-10-10 11:36:14 UTC"))

# 修改后的测试(兼容微秒精度):
expect(user.created_at).to be_within(0.1.seconds).of(Time.parse("2015-10-10 11:36:14 UTC"))

或者直接使用包含微秒的时间字符串进行断言:

expect(user.created_at).to eq(Time.parse("2015-10-10 11:36:14.042865 UTC"))

内容的提问来源于stack exchange,提问作者Anoob K Bava

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:25:55