首页 > 解决方案 > 日期。未来?有时不正确

问题描述

我有一个验证,涉及检查一个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,则验证将通过,如果它的日期大于今天在他们的时区它将失败。

标签: ruby-on-rails

解决方案


根据添加到问题和这篇文章的评论,我想出了以下解决方案。

我介绍了一种方法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 }

推荐阅读