比较日期:“日期与零比较失败”

时间:2012-11-27 23:48:44

标签: ruby-on-rails validation date

我有一个拥有许多项目的客户端模型。在项目模型中,我想验证项目开始日期是否始终在项目结束日期之前或同一天。这是我的项目模型:

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 > end_on,两次undefined method '>' for nil:NilClasscomparison of Date with nil failed一次。

我可以做些什么来让测试通过?

1 个答案:

答案 0 :(得分:1)

您正在创建一个具有以下字符串值的项目:start_on和:end_on。这不太可行。 Rails可能会试图变得聪明并解析那些,我不确定......我不会指望它。可能性正在发生一些强制,价值将被设定为零。

我会这样做:

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