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 ...

Get Learning Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.