Kleber S.
Kleber S.

Reputation: 8240

How to test a validation with conditional?

How should I test a validation with a conditional like this:

validates :age, :numericality => true, :if => :age?

This is what I have for now:

before(:each) do
  @attr = { :age => "30" }
end

it "should require a age if present" do
   Model.new(@attr.merge(:age => "foo").should_not be_valid
end

And the error message is:

expected valid? to return false, got true

But doing this, the ifis not evaluated.

Upvotes: 1

Views: 268

Answers (2)

Chowlett
Chowlett

Reputation: 46667

Have you tried :allow_nil => true instead of the :if condition?

Upvotes: 2

Taryn East
Taryn East

Reputation: 27747

Have you actually written a method called "age?" ?

I think what you're trying to do is actually covered by:

 validates :age, :numericality => true, :allow_nil => true

Upvotes: 1

Related Questions