私は Rails と Rspec に少し慣れていないため、モデルで日時の検証が正しいことをテストする方法がわかりません。開始時刻と終了時刻を持つモデル イベントを作成しましたが、開始時刻を過去にすることはできず、終了時刻は開始時刻より後にする必要があるなど、いくつかの重要な条件があります。
これらの検証を確実にするために、ValidatesTimeliness https://github.com/adzap/validates_timelinessを使用しています
私のモデルは次のとおりです。
class Event < ActiveRecord::Base
...
validates_datetime :start_date,
:after => :now,
:after_message => "Event cannot start in the past"
validates_datetime :end_date,
:after => :start_date,
:after_message => "End time cannot be before start time"
end
私のRSpecテストでは、次のものがあります。
describe Event do
let(:event) { FactoryGirl.build :event }
subject { event }
context "when start_date is before the current time" do
it {should_not allow_value(1.day.ago).
for(:start_date)}
end
context "when end_date is before or on start date" do
it {should_not allow_value(event.start_date - 1.day).
for(:end_date)}
it {should_not allow_value(event.start_date).
for(:end_date)}
end
context "when the end_date is after the start_date" do
it {should allow_value(event.start_date + 1.day).
for(:end_date)}
end
end
ただし、これは、開始日が正確な日時より前でなければならないことを実際にテストするものではありません。たとえば、モデル:today
の代わりに誤って使用した場合:now
、これらのテストもパスします。
以前は RSpec マッチャーvalidate_date
( http://www.railslodge.com/plugins/1160-validates-timeliness ) があったことをオンラインで読みましたが、これはまさに私が探していたものですが、私が知る限り、削除されました。
私の質問は、テストを改善するにはどうすればよいかということです。それに応じて成功/失敗を保証するために、最小の時間 (つまり、ミリ秒) を試行するテストを追加する必要がありますか、それともより良い方法がありますか?
前もって感謝します!