我有一个有很多项目的客户端模型。在项目模型中,我想验证项目开始日期是否始终在项目结束日期之前或同一天。这是我的项目模型:
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:NilClass
两次,comparison of Date with nil failed
一次。
我该怎么做才能使测试通过?
您正在创建一个具有 :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")