我正在尝试创建和测试一个验证,该验证应该根据记录是否在上午8点到晚上9点的时间范围内来确定是否可以保存。
在我的模型中,我有
validate :tour_times
def tour_times
if tour_time == Range.new(Time.local(tour_time.year, tour_time.month, tour_time.day, 8),Time.local(tour_time.year, tour_time.month, tour_time.day, 21, 00))
binding.pry
end
end
在我的测试中,我有以下
describe "invalid datetime" do
before do
@valid_1 = DateTime.new(2014, 10, 1, 7, 59)
end
it "should not accept times before 8am and after 9pm" do
expect(@form.update_attributes(tour_date: @valid_1.to_date, tour_time: @valid_1.to_time)).to be_falsey
end
然而,它没有注意到验证,并开始窥探。它可以节省开支。
Failure/Error: expect(@form.update_attributes(tour_date: @valid_1.to_date, tour_time: @valid_1.to_time)).to be_falsey
expected: falsey value
got: true
为什么会这样。它至少应该击中撬棍。但奇怪的是,我将条件更改为除非,并通过检查有效日期时间的测试进行了窥探。
请尝试这个
def tour_times
if error_condition
self.errors.add :field, 'Text of error'
end
end
如果您没有在验证方法中添加新错误,那么是否有效?返回true。
迭代1:我需要确保代码能够运行。始终呈现错误。
def tour_times
self.errors.add :tour_date, 'with error'
end