【问题标题】:rspec should ensure_length_of allow_nilrspec 应该确保_length_of allow_nil
【发布时间】:2013-12-25 09:39:37
【问题描述】:

型号

validates_length_of :description, :maximum => 255, :allow_nil => true

规范文件

it { should ensure_length_of(:description).is_at_most(255).allow_nil }

返回异常

Failure/Error: it { should ensure_length_of(:description).is_at_most(255).allow_nil }
 NoMethodError:
   undefined method `allow_nil' for #<Shoulda::Matchers::ActiveModel::EnsureLengthOfMatcher:0x0000000acb03e0>

请帮忙!

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    Shoulda::Matchers::ActiveModel::EnsureLengthOfMatcher 没有 allow_nil 方法。

    你可以使用allow_value:

    it { should allow_value(nil).for(:description) }
    it { should ensure_length_of(:description).is_at_most(255) }
    

    【讨论】:

      【解决方案2】:

      型号

      # frozen_string_literal: true
      
      class MyModel < ActiveRecord::Base
        validates :description, length: { maximum: 255 }, allow_nil: true
      end
      

      Rspec

      # frozen_string_literal: true
      
      describe MyModel do
        describe 'validations' do
          it { is_expected.to allow_value(nil).for(:description) }
          it { is_expected.to validate_length_of(:description).is_at_most(255) }
        end
      end
      

      附注ensure_length_of 已弃用

      【讨论】:

        【解决方案3】:

        您不需要allow_nil 987654322 @如果您只验证最大字符。

        【讨论】:

        • 我无法改变模型,我需要只写测试!这是问题:( span>
        猜你喜欢
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多