Unit Testing Conditional Validation

Hi there,

I have the following conditional validation in my model:

validates_presence_of :ext_name, :if => :is_ext?

def is_ext? ext end

ext is a boolean value in the database. If it is true the ext_name need to be supplied. Now it appears that the validation is in fact working however I wrote two unit test to make sure:

def test_restaurant_with_no_external_delivery restaurant = Restaurant.new(:ext => 0)

assert !restaurant.errors.invalid?(:ext_name)

end

def test_restaurant_with_external_delivery

  restaurant = Restaurant.new(:ext => 1)

  assert restaurant.errors.invalid?(:ext_name)

end

For some reason the second test also fails. Effectively(if i were to believe th e test) setting the ext field to true does not in fact require the presence of ext_name. Can some one please help me understand what is going wrong here?

Thanks a lot, steve

For some reason the second test also fails. Effectively(if i were to believe th e test) setting the ext field to true does not in fact require the presence of ext_name. Can some one please help me understand what is going wrong here?

You should be setting ext to true or false, not 1 or 0. Fred

Thanks for the response Fred however still no dice. I tried the following three variants(separately of course) and the second test still failed in each case:

restaurant = Restaurant.new(:ext => "false") restaurant = Restaurant.new(:ext => 'false') restaurant = Restaurant.new(:ext => false)

I did the same for true in the second case as well. Any other ideas?

Frederick Cheung wrote:

Thanks for the response Fred however still no dice. I tried the following three variants(separately of course) and the second test still failed in each case:

restaurant = Restaurant.new(:ext => "false") restaurant = Restaurant.new(:ext => 'false') restaurant = Restaurant.new(:ext => false)

You definitely want the last one. The other thing is that the errors
object is only set up when the valid? method has been called.

Fred