문제

Model

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

spec_file

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

return exeption

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>

Pls, help!

도움이 되었습니까?

해결책

There is no allow_nil method for Shoulda::Matchers::ActiveModel::EnsureLengthOfMatcher.

You could use allow_value:

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

다른 팁

Model

# 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

P.S. ensure_length_of is deprecated

You don't need allow_nil with validates_length_of if you're only validating the maximum of characters.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top