如果我无法在模型中禁止使用过去日期创建对象,如何在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

另外,您在测试中会产生很多杂音(未声明的数据),应避免这种杂音,例如,创建一个辅助函数或使用factory

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值。要在这种情况下,做的是测试falseeq false

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档