我有一个客户端模型,它有很多项目。在项目模型中,我想验证项目开始日期总是在项目结束日期之前或同一天。这是我的项目模型:比较日期:“日期与零比较失败”
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
一次。
我能做些什么来使测试通过?
修复 - 没有'零> x'。它不会工作。 – 2012-11-27 23:50:00
@pst但为什么是start_on无? – weltschmerz
所以,现在我们正在某个地方!它在哪里设置,使得'start_on'(如指定的命名参数)将更新'start_on'访问器?如果将它设置为字符串而不是实时对象,会发生什么情况?如果它是在构造函数之后设置的呢?那就是追踪。所报告的绒毛不是你正在寻找的绒毛。 – 2012-11-27 23:51:28