Tôi có validator sau trong mô hình của tôi:RSpec kiểm tra tùy chỉnh validator
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
Làm thế nào tôi có thể kiểm tra bằng RSpec?
Dưới đây là những gì tôi đã cố gắng cho đến nay: (nhờ 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
Nhưng tôi nhận được các lỗi sau đây:
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={}>
Tôi đang làm gì sai? Và làm thế nào tôi có thể đạt được mục tiêu của mình? Bất kỳ trợ giúp hoặc gợi ý nào sẽ được đánh giá cao. Cảm ơn.
Bạn nói đúng Tôi cần thêm full_messages để nhận lỗi. Tuy nhiên, như người kia đã nói, tôi cần thực sự kiểm tra việc xác nhận hợp lệ với 'hợp lệ? ' – siekfried
Đúng vậy. Tôi đã cập nhật câu trả lời. –