我有一个有很多项目的客户模型。在项目模型中,我想验证项目开始日期是否始终早于项目结束日期或与项目结束日期相同。这是我的项目模型:
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
一次。
我该怎么做才能使测试通过?