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

如何在RSpec Rails中正确翻译日期并规避I18n错误?

在RSpec中正确实现日期翻译的方法

问题场景

你遇到了两个核心问题:

  • 直接用strftime格式化日期,得到的是英文格式,无法实现本地化翻译:
    expect(page).to have_content 1.day.from_now.strftime("%d de %B de %Y %H:%M")
    
  • 尝试用I18n.l包裹strftime生成的字符串时,触发类型错误:

    I18n::ArgumentError:
    Object must be a Date, DateTime or Time object. "13 de February de 2023 20:00" given.
    对应的错误代码:

    expect(page).to have_content I18n.l(1.day.from_now.strftime("%d de %B de %Y %H:%M"))
    
    而视图层直接用I18n.l处理时间对象并指定格式是正常的:
    <h2>Refeição em <%= I18n.l ml.meal_date, :format => "%d de %B de %Y %H:%M" %></h2>
    

正确解决方法

I18n.l(即I18n.localize)方法的核心要求是必须接收Date/DateTime/Time类型的对象,而不是字符串。你只需要照搬视图层的写法,直接把时间对象传给I18n.l并指定格式即可:

expect(page).to have_content I18n.l(1.day.from_now, format: "%d de %B de %Y %H:%M")

优化方案(推荐)

为了避免硬编码格式字符串,更符合Rails I18n的最佳实践,可以把日期格式配置到本地化文件中。比如在config/locales/pt-BR.yml(根据你的实际语言环境调整)中添加:

pt-BR:
  time:
    formats:
      meal_date: "%d de %B de %Y %H:%M"

之后在RSpec和视图层统一使用这个命名格式:

# RSpec 中
expect(page).to have_content I18n.l(1.day.from_now, format: :meal_date)
# 视图层
<h2>Refeição em <%= I18n.l ml.meal_date, format: :meal_date %></h2>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:20:41