In an ActiveRecord (or ActiveModel) I would like the following spec to pass
it { should allow_value("").for(:my_string) }
it { should_not allow_value(nil).for(:my_string) }
I have tried
validates :my_string, {
:length => { :in => 0..255 },
:presence => true,
:allow_blank => true,
:allow_nil => false,
}
and also
validates :my_string, {
:length => { :in => 0..255 },
:allow_blank => true,
:allow_nil => false,
}
But either it allows both "" and nil or none of them.
This works for me
validates :my_string, length: { in: 0..255, allow_nil: false }
If you just want to validate that the field is not null, but don't care about blank/empty strings, this works:
validates :my_string, length: { minimum: 0, allow_nil: false, message: "can't be nil" }
You can try doing:
validates :my_string, exclusion: { in: [nil]}
It is part of the validations themselves in ActiveRecord.
I've tried the others and all of them are very compliated or allow nil too.
You might need to do a custom validation for this:
validates :my_string, :length => { :in => 0..255 }
validate :my_string_is_valid
def my_string_is_valid
self.errors.add :base, 'My string can not be nil' if self.my_string.nil?
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With