我在我的模型如下驗證:RSpec的測試自定義驗證
class ContinuumValidator < ActiveModel::Validator
def validate(record)
if !record.end_time.nil? and record.end_time < record.start_time
record.errors[:base] << "An event can not be finished if it did not start yet..."
end
end
end
class Hrm::TimeEvent < ActiveRecord::Base
validates_with ContinuumValidator
end
如何使用Rspec的我測試它?
這裏是我到目前爲止已經試過:(感謝zetetic)
describe "validation error" do
before do
@time_event = Hrm::TimeEvent.new(start_time: "2012-10-05 10:00:00", end_time: "2012-10-05 09:00:00", event_type: 2)
end
it "should not be valid if end time is lower than start time" do
@time_event.should_not be_valid
end
it "raises an error if end time is lower than start time" do
@time_event.errors.should include("An event can not be finished if it did not start yet...")
end
end
,但我得到了以下錯誤:
1) Hrm::TimeEvent validation error raises an error if end time is lower than start time
Failure/Error: @time_event.errors.should include("An event can not be finished if it did not start yet...")
expected #<ActiveModel::Errors:0x007fd1d8e02c50 @base=#<Hrm::TimeEvent id: nil, start_time: "2012-10-05 08:00:00", end_time: "2012-10-05 07:00:00", event_type: 2, employee_id: nil, created_at: nil, updated_at: nil, not_punched: false, validated: false, replace_id: nil>, @messages={}> to include "An event can not be finished if it did not start yet..."
Diff:
@@ -1,2 +1,5 @@
-["An event can not be finished if it did not start yet..."]
+#<ActiveModel::Errors:0x007fd1d8e02c50
+ @base=
+ #<Hrm::TimeEvent id: nil, start_time: "2012-10-05 08:00:00", end_time: "2012-10-05 07:00:00", event_type: 2, employee_id: nil, created_at: nil, updated_at: nil, not_punched: false, validated: false, replace_id: nil>,
+ @messages={}>
我在做什麼錯?我怎樣才能達到我的目標? 任何幫助或建議,將不勝感激。 謝謝。
你說得對,我需要添加full_messages來獲取錯誤。然而像其他人說的那樣,我需要實際測試驗證'有效嗎?' – siekfried 2013-02-28 13:47:02
沒錯。我更新了答案。 – 2013-02-28 13:51:01