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

奇妙なことに、このテストを実行すると 3 つのエラーが発生します。これらはすべてif start_on > end_on、検証メソッドのこの行を参照しており、 undefined method '>' for nil:NilClass2 回と1 回と表示されcomparison of Date with nil failedています。

テストに合格するにはどうすればよいですか?

4

1 に答える 1

1

:start_on と :end_on の文字列値を持つプロジェクトを作成しています。それはうまくいかないでしょう。Rails は賢く、それらを解析しようとするかもしれません。何らかの強制が行われており、値が nil に設定されている可能性があります。

私はこれを行います:

project = Project.new(client_id: 1, 
                      start_on: 2.days.from_now.to_date, 
                      end_on: Time.now.to_date, 
                      title: "Project title")
于 2012-11-28T00:06:28.757 に答える