为什么测试因验证而失败?

Why are tests failing due to validation?

我正在为一个应用程序编写测试,运行遇到一个问题。

我的模型有下一个验证:

  def correct_date
    errors.add(:occured_at, 'must be in past or present time') if occured_at > 5.minutes.from_now
  end

当我 运行 对模型进行最简单的测试时,它们都失败了。

  describe 'associations' do
    it { should belong_to(:category).optional }
  end

我收到一个错误:

     Failure/Error: errors.add(:occured_at, 'must be in past or present time') if occured_at > 5.minutes.from_now
     
     NoMethodError:
       undefined method `>' for nil:NilClass

默认情况下,该测试将通过简单的 Model.new 调用创建一个新对象(其中 Model 是正在测试的模型 class)。在您的情况下,Model.new 不会生成有效对象,因此您需要告诉 Rspec 用于这些测试的主题:

describe 'associations' do
  subject { FactoryBot.create(:whatever_the_factory_is_called) }

  it { should belong_to(:category).optional }
end

您还应该修复 correct_date 验证方法以处理 occurred_at.nil?;验证它不是 nil in correct_date:

def correct_date
  if(occurred_at.nil?)
    # complain
  elsif(occurred_at > 5.minutes.from_now)
    errors.add(:occured_at, 'must be in past or present time')
  end
end

或单独验证存在并跳过 > when occurred_at.nil?:

validates :occurred_at, presence: true

def correct_date
  errors.add(:occured_at, 'must be in past or present time') if occurred_at && occured_at > 5.minutes.from_now
end

在数据库中创建 occurred_atnot null 也是可取的。

如果 occurred_at 确实是可选的,那么您只需要更新 correct_date 以说明 occurred_at.nil?:

def correct_date
  errors.add(:occured_at, 'must be in past or present time') if occurred_at && occured_at > 5.minutes.from_now
end