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.)
One of the simplest tests is to require a validation if, and only if, another
condition is met. The
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
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
method will only perform its test ...