簡體   English   中英

rspec應該確保_length_of allow_nil

[英]rspec should ensure_length_of allow_nil

模型

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

spec_file

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>

請幫忙!

對於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) }

模型

# frozen_string_literal: true

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

規格

# 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

PS sure_length_of已棄用

如果僅驗證最大字符allow_nil ,則不需要帶有validates_length_of allow_nil

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM