【问题标题】:Shoulda Matcher with custom validation causing all shoulda validations to fail具有自定义验证的应该匹配器导致所有应该验证失败
【发布时间】:2015-09-17 23:34:21
【问题描述】:

我遇到了一个问题,我的模型上的自定义验证导致所有 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

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

【问题讨论】:

    标签: ruby-on-rails validation rspec


    【解决方案1】:

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

    当您在 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 的新实例。属性将被预先设置,这意味着您的实例默认有效,并且测试现在应该能够正确测试每个单独的验证。

    【讨论】:

    • 我认为我的例子不是最好的。我正在使用的这个验证是在不同的对象上调用一个字段。我想我只需要用这个在工厂中创建一个有效的嵌套对象。我认为这有帮助,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多