具有自定义验证的Shoulda Matcher导致所有shoulda验证失败

时间:2015-09-17 23:34:21

标签: ruby-on-rails validation rspec

我遇到的问题是我的模型上的自定义验证导致所有的shoulda验证失败。

本质:

class User < ActiveRecord::Base
  validates_presence_of :name
  validate :some_date_validation

  private

  def some_date_validation
    if date_given > birthday
      errors.add(:birthday, "Some sort of error message")
    end
  end
end

然后在规范中:

require 'rails_helper'

RSpec.describe User, type: :model do
  describe "shoulda validations" do
    it { should validate_presence_of(:name) }
  end
end

这将导致我的测试失败,因为其他验证将无法通过。这是为什么?

1 个答案:

答案 0 :(得分:4)

您需要使用默认情况下有效的对象实例进行测试。

当您在Rspec测试中使用隐式主题时,Rspec将使用默认初始值设定项为您创建待测对象的新实例。在这种情况下,User.new。此实例将无效,因为name既不存在也不会自定义验证通过。

如果您正在使用工厂(例如factory_girl),那么您应该创建一个User工厂,该工厂设置验证通过的所有属性。

FactoryGirl.define do
  factory :user do
    name "John Doe"
    date_given Time.now
    birthday 25.years.ago
  end
end

然后在测试中使用它

require 'rails_helper'

RSpec.describe User, type: :model do
  describe "shoulda validations" do
    subject { build(:user) }
    it { should validate_presence_of(:name) }
  end
end

您现在已明确将测试主题设置为您工厂创建的User新实例。这些属性将被预先设置,这意味着您的实例默认是有效的,并且测试现在应该能够正确地测试每个单独的验证。