2012-11-27 74 views
0

我有一个客户端模型,它有很多项目。在项目模型中,我想验证项目开始日期总是在项目结束日期之前或同一天。这是我的项目模型:比较日期:“日期与零比较失败”

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一次。

我能做些什么来使测试通过?

+0

修复 - 没有'零> x'。它不会工作。 – 2012-11-27 23:50:00

+0

@pst但为什么是start_on无? – weltschmerz

+0

所以,现在我们正在某个地方!它在哪里设置,使得'start_on'(如指定的命名参数)将更新'start_on'访问器?如果将它设置为字符串而不是实时对象,会发生什么情况?如果它是在构造函数之后设置的呢?那就是追踪。所报告的绒毛不是你正在寻找的绒毛。 – 2012-11-27 23:51:28

回答

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") 
+0

完美,那固定了测试,谢谢!另外,我将我的项目模型更改为使用[date_validator gem](http://blog.codegram.com/2011/2/2/date-validation-with-rails-3),所以现在代码更清晰了:'validates :end_on,date:{after_or_equal_to::start_on}和'validates:start_on,date:{before_or_equal_to::end_on}' – weltschmerz