ruby-on-rails - 日期。未来?有时不正确
问题描述
我有一个验证,涉及检查一个compdate
字段是否在未来。该compdate
字段的类型为日期。对此的自定义验证如下所示
class Game
validate :compdate_not_in_future
def compdate_not_in_future
return if compdate.nil?
return unless compdate.future?
errors.add(:compdate, 'cannot be in the future')
end
end
我用这样的 rspec 测试对此进行了测试。
it { expect(build(:game, compdate: Date.today).valid?).to be true }
it { expect(build(:game, compdate: 1.day.from_now.to_date).valid?).to be true }
这些测试可能会失败,具体取决于一天中的时间。我怀疑这是由于我的时区与 UTC 的关系。如何对此进行测试并更正验证器,以便无论用户在哪个时区,它都可以按预期工作,例如,如果用户输入了今天在他们的时区中的 compdate,则验证将通过,如果它的日期大于今天在他们的时区它将失败。
解决方案
根据添加到问题和这篇文章的评论,我想出了以下解决方案。
我介绍了一种方法match_zone
,该方法具有游戏所在的时区。然后班级有
class Game
validate :compdate_not_in_future
def compdate_not_in_future
return if compdate.nil?
Time.use_zone(match_zone) do
return unless compdate.future?
end
errors.add(:compdate, 'cannot be in the future')
end
end
测试是这样的:
it { expect(build(:game, compdate: Time.use_zone(match_zone) { Date.current }).valid?).to be true }
it { expect(build(:game, compdate: Time.use_zone(match_zone) { Date.current + 1.day}).valid?).to be true }
推荐阅读
- javascript - 回调箭头函数返回未定义
- python - 如何摆脱此列表中的子元组?
- python - 在 pygame 上开发游戏时出现错误
- swift - 从可解码模型中解码带有空格的网址
- node.js - 有没有办法在重新加载时保存画布的状态?
- reactjs - 如何使用 reactjs 正确获取与 conatct 类一起使用的记录列表
- r - rbind 添加一行包含日期值的行
- r - R 从 if-else 和 for 循环到更高效的函数
- python - 将 python 代码与 Visual Studio c# 集成
- mongodb - 如何将元素推送到 Nest.js 上 MongoDB 文档中的数组?