【问题标题】:Comparing dates: "comparison of Date with nil failed"比较日期:“日期与 nil 的比较失败”
【发布时间】:2012-11-27 23:48:43
【问题描述】:

我有一个包含许多项目的客户模型。在项目模型中,我想验证项目开始日期是否始终早于项目结束日期或与项目结束日期相同。这是我的项目模型:

class Project < ActiveRecord::Base
  attr_accessible :end_on, :start_on, :title

  validates_presence_of :client_id, :end_on, :start_on, :title
  validate :start_has_to_be_before_end

  belongs_to :clients

  def start_has_to_be_before_end
    if start_on > end_on
        errors[:start_on] << " must not be after end date."
        errors[:end_on] << " must not be before start date."
    end
  end
end

我的应用程序按预期工作,并在验证失败时给我指定的错误。

但是,在我对项目的单元测试中,我试图涵盖这种情况,故意将开始日期设置在结束日期之后:

test "project must have a start date thats either on the same day or before the end date" do
    project = Project.new(client_id: 1, start_on: "2012-01-02", end_on: "2012-01-01", title: "Project title")
    assert !project.save, "Project could be saved although its start date was after its end date"
    assert !project.errors[:start_on].empty?
    assert !project.errors[:end_on].empty?
end

奇怪的是,运行这个测试给了我三个错误,在我的验证方法中都引用了if start_on &gt; end_on这一行,说两次undefined method '&gt;' for nil:NilClass和一次comparison of Date with nil failed

我该怎么做才能使测试通过?

【问题讨论】:

  • 修复 - 没有 nil &gt; x。它不会起作用。
  • @pst 但是为什么 start_on 为零?
  • 所以,现在我们到了某个地方!它在哪里设置以便start_on(指定为命名参数)将更新start_on 访问器?如果它被设置为字符串而不是实时对象会发生什么?如果在构造函数之后设置呢?即,循迹而行。报告的绒毛不是您要查找的绒毛。

标签: ruby-on-rails validation date


【解决方案1】:

您正在创建一个包含 :start_on 和 :end_on 字符串值的项目。这不太可能奏效。 Rails 可能会尝试变得聪明并解析这些,我不确定.. 我不会指望它。很可能发生了一些强制,并且值被设置为 nil。

我会这样做:

project = Project.new(client_id: 1, 
                      start_on: 2.days.from_now.to_date, 
                      end_on: Time.now.to_date, 
                      title: "Project title")

【讨论】:

  • 完美,解决了测试问题,谢谢!另外,我将项目模型更改为使用date_validator gem,所以现在代码更清晰:validates :end_on, date: { after_or_equal_to: :start_on }validates :start_on, date: { before_or_equal_to: :end_on }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多