O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Beyond Simple Declarations

The tests shown above are valuable, but also limited. They test a single value against a limited set of possibilities and don’t allow interactions among different values. While Rails makes it easy to do easy things, it fortunately also make it fairly easy to do more complicated things. (You can find these more complicated examples in ch07/guestbook006.)

Test It Only If

One of the simplest tests is to require a validation if, and only if, another condition is met. The :if parameter, available on every test, lets you define those conditions. (There’s a corresponding :unless parameter that works similarly but in the opposite direction.) The easiest way to use :if is to point it at a method that returns a boolean value. That way your code can stay readable, and you can put whatever complications are involved in the test into a more maintainable and testable separate method.

This example uses the value of the :can_send_email field to determine whether the :description field must have a value. Neither is a field that would typically need much validation, but they can easily be treated as connected:

# if person says 'can send email', then we'd like them to fill their
# description in, so we understand who it is we're sending mail to
validates_presence_of :description, :if => :require_description_presence?
  
# we define the supporting condition here
def require_description_presence?
  self.can_send_email
end

The validates_presence_of method will only perform its test ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required