如何解决如果我无法在模型中禁止使用过去日期创建对象,如何在Rails上使用RSpec过去日期进行测试?
我有一个模型约会,禁止使用过去的日期创建对象,或者如果字段日期是过去的,则禁止更新。
class Appointment < ApplicationRecord
belongs_to :user
...
validate :not_past,on: [:create,:update]
private
...
def not_past
if day.past?
errors.add(:day,'...')
end
end
end
但是我需要使用RSpec制作一个测试文件,以测试如果字段日期是过去日期,则是否真的不能编辑该文件。
require 'rails_helper'
RSpec.describe Appointment,type: :model do
...
it 'Cannot be edited if the date has past' do
@user = User.last
r = Appointment.new
r.day = (Time.now - 2.days).strftime("%d/%m/%Y")
r.hour = "10:00"
r.description = "Some Description"
r.duration = 1.0
r.user = @user
r.save!
x = Appointment.last
x.description = "Other"
expect(x.save).to be_falsey
end
...
end
麻烦的是,由于发生错误,导致测试无法准确进行,该错误禁止在过去一天创建约会对象。
我该怎么做才能使它生效,或者甚至可以使一个伪造的对象具有过期日期,以便最终对其进行测试?
解决方法
您可以使用update_attribute跳过验证。
it 'Cannot be edited if the date has past' do
@user = User.last
r = Appointment.new
r.day = (Time.now - 2.days).strftime("%d/%m/%Y")
r.hour = "10:00"
r.description = "Some Description"
r.duration = 1.0
r.user = @user
r.save!
x = Appointment.last
x.description = "Other"
r.update_attribute(:day,(Time.now - 2.days).strftime("%d/%m/%Y"))
expect(x.save).to be_falsey
end
此外,您的测试中还会有很多杂音(未声明的数据),应通过例如创建辅助函数或使用factories。
it 'Cannot be edited if the date has past' do
appointment = create_appointment
appointment.update_attribute(:day,(Time.now - 2.days).strftime("%d/%m/%Y"))
appointment.description = 'new'
assert(appointment.valid?).to eq false
end
def create_appointment
Appointment.create!(
day: Time.now.strftime("%d/%m/%Y"),hour: '10:00',description: 'description',duration: 1.0,user: User.last
)
end
还要测试falsey
,它也将匹配nil值。在这种情况下,您想要做的是用false
测试eq false
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。