gpt4 book ai didi

ruby-on-rails - RSpec 测试自定义验证器

转载 作者:数据小太阳 更新时间:2023-10-29 07:02:14 27 4
gpt4 key购买 nike

我的模型中有以下验证器:

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={}>

我做错了什么?我怎样才能实现我的目标?任何帮助或建议将不胜感激。谢谢。

最佳答案

问题是您期望 @time_event.errors 表现得像一个字符串数组。它没有,它返回 ActiveModel::Errors。正如其他人指出的那样,您还需要通过调用 valid? 来触发验证:

it "raises an error if end time is lower than start time" do
@time_event.valid?
@time_event.errors.full_messages.should include("An event can not be finished if it did not start yet...")
end

关于ruby-on-rails - RSpec 测试自定义验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136497/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com