模型
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>
请帮助!
答案 0 :(得分:7)
allow_nil
没有Shoulda::Matchers::ActiveModel::EnsureLengthOfMatcher
方法。
您可以使用allow_value
:
it { should allow_value(nil).for(:description) }
it { should ensure_length_of(:description).is_at_most(255) }
答案 1 :(得分:1)
模型
# 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
答案 2 :(得分:0)
如果您只验证字符的最大值,则allow_nil
不需要validates_length_of
。