应该在RSpec中使用改革形式匹配“validate_length_of”

问题描述 投票:0回答:1

我正在使用ReformRSpec宝石为我的表格(使用Shoulda Matchers gem)设置规格。我想弄清楚为什么我有验证问题。

我的实际配置:

  ruby '2.5.1'
  gem 'rails', '~> 5.2.0'
  gem 'rspec-rails', '~> 3.8'
  gem 'shoulda-matchers', '~> 4.0'
  gem 'reform-rails', '~> 0.1'

我已经在我的表单中尝试了不同种类的长度验证。但没有什么能让事情变得更好。

这是用于测试的最小形式:

# frozen_string_literal: true

class UserForm < Reform::Form
  # == Properties  ==========================================================
  property :nickname


  # == Validations ==========================================================
  validates :nickname, presence: true, length: { minimum: 3, maximum: 100 } 
end

这是规格:

# frozen_string_literal: true

RSpec.describe UserForm, type: :model do
  subject { described_class.new(User.new) }

  it { is_expected.to validate_presence_of :nickname }
  it { is_expected.to validate_length_of(:nickname).is_at_least(3).is_at_most(100) }
end

请注意,validate_presence_of匹配器完美运行。

我有RSpec输出:

  1) UserForm should validate that the length of :nickname is between 3 and 100
     Failure/Error: it { is_expected.to validate_length_of(:nickname).is_at_least(3).is_at_most(100) }

       Expected UserForm to validate that the length of :nickname is between
       3 and 100, but this could not be proved.
         After setting :nickname to ‹"xxx"›, the matcher expected the
         UserForm to be valid, but it was invalid instead, producing these
         validation errors:

         * nickname: ["is too short (at least 3 characters)"]

我显然除了使这些验证工作。

我希望我能在这里找到帮助:)

ruby-on-rails rspec shoulda reform
1个回答
0
投票

Reform is known not to work with shoulda-matchers。基本上,shoulda-matchers中的所有模型匹配器都通过以下方式工作:

  • 制作测试类的新实例。
  • 在该实例上设置属性。
  • 在那个实例上调用validate
  • errors读取任何可能的验证错误。

但是,Reform doesn't work this way;如果不单独在表单对象上设置属性,然后调用valid?,则使用要在表单对象上设置的属性调用validate,然后在设置过程中验证这些属性。所以这可能是你得到这个错误的原因 - 因为shoulda-matchers试图手动设置属性,然后validate将它们吹走。

不幸的是,如果没有编写某种适配器,就没有办法让shoulda-matchers与Reform一起工作。我们不打算很快将这个添加到宝石中,但我们将采取公关!除此之外,显然the Reform team was talking about making some RSpec matchers本质上属于shoulda-matchers,但我不确定在那里取得了多大进展,如果有的话。

对不起我无法提供帮助:/

© www.soinside.com 2019 - 2024. All rights reserved.