5.6 Exercises

    We saw in Section 5.3 that the have_content RSpec matcher sometimes
matches too broadly, leading us to temporarily comment out the “Contact”
line in the footer to avoid an erroneous passing test (Listing 5.18). To
fix this, Listing 5.38 introduces Capybara’s have_selector method, which
allows us to test the presence of specific HTML tags. By deleting and
then restoring the “Contact” h1 in Listing 5.21, verify that the code in
Listing 5.38 correctly fails even when the footer isn’t commented out.
    The code in Listing 5.30 for testing static pages is compact but is
still a bit repetitive. RSpec supports a facility called shared examples
to eliminate this kind of duplication. By following the example in
Listing 5.39, fill in the missing tests for the About and Contact pages.
Note that the let command, introduced briefly in Listing 3.31, creates a
local variable with the given value on demand (i.e., when the variable
is used), in contrast to an instance variable, which is created upon
assignment. (Listing 5.39 also incorporates the use of have_selector
from Listing 5.38.)
    You may have noticed that our tests for the layout links test the
routing but don’t actually check that the links on the layout go to the
right pages. One way to implement these tests is to use visit and
click_link inside the RSpec integration test. Fill in the code in
Listing 5.40 to verify that all the layout links are properly defined.
    Eliminate the need for the full_title test helper in Listing 5.29 by
writing tests for the original helper method, as shown in Listing 5.41.
(You will have to create both the spec/helpers directory and the
application_helper_spec.rb file.) Then include it into the test using
the code in Listing 5.42. Verify by running the test suite that the new
code is still valid. Note: Listing 5.41 uses regular expressions, which
we’ll learn more about in Section 6.2.4. (Thanks to Alex Chaffee for the
suggestion and code used in this exercise.)