多くのプロジェクトを持つクライアントモデルがあります。プロジェクト モデルでは、プロジェクトの開始日が常にプロジェクトの終了日よりも前または同じ日であることを検証したいと考えています。これは私のプロジェクトモデルです:
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:NilClass
2 回と1 回と表示されcomparison of Date with nil failed
ています。
テストに合格するにはどうすればよいですか?