Frage

I am not able to get my tests passing for where the field can be empty string but where it can't be null.

I used this stackeroverflow post for a litte help

But can't find much more to help me.

In my schema.rb file I see:

t.string   "CUSTID",        :limit => 8,     :default => "",     :null => false

When I run an rspec test against this, my validates still allows it to be null. Could you please explain why my test (below) would fail?

it 'CUSTID may not be nil' do
  should_not allow_value(nil).for(:CUSTID)
end

then I tried these validations methods separate in the model.

validates :TNCUSTID, :allow_nil => false
validates :TNCUSTID,  :format => {:with => /^(CU)(\d{6})$|(^$)/ }

and even leaving the validation out completely

#validates :TNCUSTID, :allow_nil => false

In all cases my "Should not be nil" test case fails for custid


My ultimate goal is to say that the value can be either this format (regex above), can be empty string BUT is can never be null according to the database.

Can someone please enlighten me

War es hilfreich?

Lösung

Use validates

validates :TNCUSTID, presence: true
validates :TNCUSTID, :format => {:with => /^(CU)(\d{6})$|(^$)/ }

And in your tests

should validate_presence_of :TNCUSTID

And for email

should validate_format_of(:email).not_with('test@test').with_message(/invalid/)

From this StackOverflow question

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top