【发布时间】: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 > end_on这一行,说两次undefined method '>' for nil:NilClass和一次comparison of Date with nil failed。
我该怎么做才能使测试通过?
【问题讨论】:
-
修复 - 没有
nil > x。它不会起作用。 -
@pst 但是为什么 start_on 为零?
-
所以,现在我们到了某个地方!它在哪里设置以便
start_on(指定为命名参数)将更新start_on访问器?如果它被设置为字符串而不是实时对象会发生什么?如果在构造函数之后设置呢?即,循迹而行。报告的绒毛不是您要查找的绒毛。
标签: ruby-on-rails validation date