6.2.2 Validating Presence

Perhaps the most elementary validation is presence, which simply
verifies that a given attribute is present. For example, in this section
we’ll ensure that both the name and email fields are present before a
user gets saved to the database. In Section 7.3.3, we’ll see how to
propagate this requirement up to the signup form for creating new users.

We’ll start with a test for the presence of a name attribute. Although
the first step in TDD is to write a failing test (Section 3.2.1), in
this case we don’t yet know enough about validations to write the proper
test, so we’ll write the validation first, using the console to
understand it. Then we’ll comment out the validation, write a failing
test, and verify that uncommenting the validation gets the test to pass.
This procedure may seem pedantic for such a simple test, but I have seen
many “simple” tests that actually test the wrong thing; being meticulous
about TDD is simply the only way to be confident that we’re testing the
right thing. (This comment-out technique is also useful when rescuing an
application whose application code is already written but—quelle
horreur!—has no tests.)

The way to validate the presence of the name attribute is to use the
validates method with argument presence: true, as shown in Listing 6.6.
The presence: true argument is a one-element options hash; recall from
Section 4.3.4 that curly braces are optional when passing hashes as the
final argument in a method. (As noted in Section 5.1.1, the use of
options hashes is a recurring theme in Rails.)