Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top