Shoulda-matchers 不适用于 PORO

Shoulda-matchers not working for PORO

所以我有以下规范:

require 'rails_helper'

class SpecRecord
  # include ActiveModel::Model
  include ActiveModel::Validations
  attr_accessor :email
  validates :email, rfc_compliant: true
end

describe RfcCompliantValidator do
  subject { SpecRecord.new }

   it { is_expected.to allow_value('test@example.com').for(:email) }
   it { is_expected.to allow_value('disposable.style.email.with+symbol@example.com').for(:email) }
   it { is_expected.to allow_value('other.email-with-dash@example.net').for(:email) }
   it { is_expected.to allow_value('x@example.org').for(:email) }
   it { is_expected.to allow_value('test@example.123-online.tv').for(:email) }
   it { is_expected.to allow_value("0123456789#!$%&'*+-/=?^_`{}|~@example.org.co.uk").for(:email) }

   it { is_expected.to_not allow_value('john316').for(:email) }
   it { is_expected.to_not allow_value('test@example..com').for(:email) }
   it { is_expected.to_not allow_value('this\ still\"not\allowed@example.com').for(:email) }
   it { is_expected.to_not allow_value('test@ex:amp,le.com').for(:email) }
   it { is_expected.to_not allow_value('t:est@example.com').for(:email) }
   it { is_expected.to_not allow_value('te,st@example.com').for(:email) }
   it { is_expected.to_not allow_value('te()st@example.com').for(:email) }
   it { is_expected.to_not allow_value('te[]st@example.com').for(:email) }
   it { is_expected.to_not allow_value('te<>st@example.com').for(:email) }
   it { is_expected.to_not allow_value('te"st@example.com').for(:email) }
   it { is_expected.to_not allow_value("test@exampledotcom").for(:email) }
   it { is_expected.to_not allow_value("testexample").for(:email) }
   it { is_expected.to_not allow_value("test@example.com123").for(:email) }
   it { is_expected.to_not allow_value("78901234567890123456789012345678901234567890123456789012345678901212+x@example.com").for(:email) }
 end

rails_helper中我定义了以下内容:

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    # Choose a test framework:
    with.test_framework :rspec

    # Choose one or more libraries:
    # with.library :active_record
    with.library :active_model
    with.library :action_controller
    # Or, choose the following (which implies all of the above):
    # with.library :rails
  end
end

在我利用 allow_value 的其他测试中,这些测试似乎有效,但由于某种原因,此处未找到 allow_value。有什么想法吗?

allow_valueShoulda::Matchers::ActiveModel 模块的一部分,用于范围界定。

此模块是否包含在测试范围内取决于正在测试的对象是否通过传递给 describe 块的选项 type 标记为 :model 对象。 Source and Source for RSpec configuration

由于您的规范未将 RfcCompliantValidator 标记为 :model,因此这些方法未包含在测试范围内。

要解决这个问题,您需要做的就是将其标记为

describe RfcCompliantValidator, type: :model do 
   ###

AllowValueMatcher 将在您的测试中可用。