10.3 Layouts
At this point, our app is looking pretty good, but there are two significant blemishes: The HTML code for the three pages is highly repetitive, and navigating by hand from page to page is rather cumbersome. We’ll fix the first blemish in this section, and the second in Section 10.4. (And of course our app doesn’t yet detect palindromes, which is the subject of Section 10.5.)
If you followedLearn Enough CSS & Layout to Be Dangerous, you’ll know that theLayoutin the title referred to page layout generally—using Cascading Style Sheets to move elements around on the page, align them properly, etc.— but we alsosawthat doing this properly requires defininglayout templatesthat capture common patterns and eliminate duplication.
In the present case, each of our site’s pages has the same basic structure, as shown in Listing 10.10.
Listing 10.10:The HTML structure of our site’s pages.
<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample Apptitle> <linkrel="stylesheet"type="text/css"href="/stylesheets/main.css"> <linkhref="https://fonts.googleapis.com/css?family=Open+Sans:300,400"rel="stylesheet"> head> <body><ahref="/"class="header-logo"><imgsrc="/images/logo_b.png"alt="Learn Enough logo"> a> <divclass="container"><divclass="content">div> div> body> html>
Everything except the page-specific content (indicated by the highlighted HTML comment) is the same on each page. InLearn Enough CSS & Layout to Be Dangerous, we eliminated this duplication usingJekyll templates; in this tutorial, we’ll useSinatra layoutsinstead.
Now, our site is currently working, in the sense that each page has the proper content at this stage of development. We’re about to make a change that involves moving around and deleting a bunch of HTML, and we’d like to do this without breaking the site. Does that sound like something we’ve seen before?
它的确。这就是问题m we faced in Chapter 8 when we developed and then refactored the palindrome gem. In that case, we wrote automated tests to catch any regressions, and in this case we’re going to do the same. (I started making websites long before automated testing of web applications was possible, much less the norm, and believe me, automated tests are ahugeimprovement over testing web apps by hand.)
To get started, we’ll add some more gems to ourGemfile, this time in agroupcalled:testthat indicates gems that are needed only for tests. The result appears in Listing 10.11.
Listing 10.11:Adding gems for testing.
Gemfile
source'https://rubygems.org'ruby'3.1.1'# Change this line if you're using a different Ruby version.gem'sinatra','2.2.0'gem'puma','5.6.4'gem'rerun','0.13.1'group:testdogem'minitest','5.15.0'gem'minitest-reporters','1.5.0'gem'rack-test','1.1.0'gem'rake','13.0.6'gem'nokogiri','1.13.3'end
We then install the gems as usual:
If you encounter an error while installingnokogiri(which is unfortunately common), you’ll have to apply your technical sophistication (Box 1.1) to resolve the issue; I especially recommend the “Google the error message” algorithm for this case.
We’ll factor out common elements needed in all tests into a test helper file, while also creating a file for our initial site pages tests:
The test helper requires all the necessary gems, and also includes the app itself usingrequire_relative, which requires files relative to the current directory. The result appears in Listing 10.12.
Listing 10.12:The initial test helper.
test/test_helper.rb
ENV[“RACK_ENV”] ='test'require_relative'../app'require'rack/test'require'nokogiri'require'minitest/autorun'require'minitest/reporters'Minitest::Reporters.use!
We then need to create aRakefile告诉耙utility how to run the tests:
The contents are shown in Listing 10.13.
Listing 10.13:Configuring耙to run tests.
Rakefile
require'rake/testtask'
We’ll put the result of Listing 10.13 to good use in a moment, but first we need to write some tests. We’ll start with super-basic tests so that the app serves upsomething, as indicated by theHTTP response code200 (OK), which we can do like this:
Here we use thegetcommand in the test to issue aGETrequest to the root URL /, which automatically creates an object calledlast_responseas a side effect. We can then use a minitest assertion (Section 8.2) using the boolean methodok?, which is also available automatically. The result is a test that makes sure the server responded properly to the request.
Applying the above discussion to the About and Palindrome Detector pages as well, and combining them with configuration code pulled right from theofficial Sinatra documentation on tests, we arrive at our initial test suite, shown in Listing 10.14.
Listing 10.14:Our initial test suite.GREEN
test/site_pages_test.rb
require_relative'test_helper'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddeftest_indexget'/'assert last_response.ok?enddeftest_aboutget'/about'assert last_response.ok?enddeftest_palindromeget'/palindrome'assert last_response.ok?end end
With the setup in Listing 10.13, we can use耙to execute the test suite as follows:
Listing 10.15:GREEN
$bundleexec耙test3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
Also note that Listing 10.13 has followed the common Ruby convention of making running the test suite the default (an indication of how important tests are in the Ruby community), so we can actually just run耙by itself:3
Listing 10.16:GREEN
$bundleexec耙3 tests, 3 assertions, 0 failures, 0 errors, 0 skips
We’ll continue to use耙testfor clarity, but it’s good to know about this alternative convention.
The tests in Listing 10.14 are a fine start, but they really only check if the pages are there at all. It would be nice to have a slightly more stringent test of the HTML content, though nottoostringent—we don’t want our tests to make it hard to make changes in the future. As a middle ground, we’ll check that each page in the site has anh1tag somewhere in the document.
In order to do this, we’ll write a short function intest_helper.rbto return adocobject, akin to thedocumentobjectin JavaScript. We actually already know pretty much how to make it based on our work in Section 9.3, where we saw how to use Nokogiri to create a document from HTML, like this:
The only extra ingredient is the knowledge that Sinatra’s HTTP response objects always have abodyattribute representing the HTML body (the full page, not just thebodytag). This means we can definedocas shown in Listing 10.17.
Listing 10.17:What’s up, Doc?
test/test_helper.rb
ENV[“RACK_ENV”] ='test'require_relative'../app'require'rack/test'require'nokogiri'require'minitest/autorun'require'minitest/reporters'Minitest::Reporters.use!# Returns the document.defdoc(response)Nokogiri::HTML(response.body)end
Now we’re ready to usedocto find theh1(if any) on the page. One possibility would be to usedoc.cssas in, e.g., Listing 9.12:
In the present case, though, we only need to see if there’sanyh1tag, so we only need the first element:
This would work fine, but this is such a common case that Nokogiri has a special method for it, calledat_css:
Because this will benilif there’s noh1and non-nilotherwise, we can use a simple assertion, like this:
Adding this to each page in our site yields the updated test suite shown in Listing 10.18.
Listing 10.18:Adding assertions for the presence of anh1tag.GREEN
test/site_pages_test.rb
require_relative'test_helper'classPalindromeAppTest<Minitest::TestincludeRack::Test::MethodsdefappSinatra::Applicationenddeftest_indexget'/'assert last_response.ok?assert doc(last_response).at_css('h1')enddeftest_aboutget'/about'assert last_response.ok?assert doc(last_response).at_css('h1')enddeftest_palindromeget'/palindrome'assert last_response.ok?assert doc(last_response).at_css('h1')end end
By the way, some programmers adopt the convention of only ever having one assertion per test, whereas in Listing 10.18 we have two. In my experience, the overhead associated with setting up the right state (e.g., duplicating the calls toget) makes this convention inconvenient, and I’ve never run into any trouble from including multiple assertions in a test.
The tests in Listing 10.18 should now beGREENas required:
Listing 10.19:GREEN
$bundleexec耙test3 tests, 6 assertions, 0 failures, 0 errors, 0 skips
At this point, we’re ready to use a Sinatra layout to eliminate duplication. Our first step is to remove the extraneous material from our pages, leaving only the core content, as shown in Listing 10.20, Listing 10.21, and Listing 10.22. (This is why the body content wasn’t fully indented before.)
Listing 10.20:The core Home (index) view.
views/index.erb
<h1>Sample Sinatra Apph1><p>This is the sample Sinatra app for<ahref="https://www.learnenough.com/ruby-tutorial"><em>Learn Enough Ruby to Be Dangerousem>a>。学习更多关于the <ahref="/about">Abouta> page. p><p>Click the <ahref="https://en.wikipedia.org/wiki/Sator_Square">Sator Squarea> below to run the custom <ahref="/palindrome">Palindrome Detectora>。p><aclass="sator-square"href="/palindrome"><imgsrc="/images/sator_square.jpg"alt="Sator Square"> a>
Listing 10.21:The core About view.
views/about.erb
<h1>Abouth1><p>This site is the final application in <ahref="https://www.learnenough.com/ruby-tutorial"><em>Learn Enough Ruby to Be Dangerousem>a> by <ahref="https://www.michaelhartl.com/">Michael Hartla>, a tutorial introduction to the <ahref="https://www.ruby-lang.org/en/">Ruby programming languagea> that is part of <ahref="https://www.learnenough.com/">LearnEnough.coma>。p><p><em>Learn Enough Ruby to Be Dangerousem> is a natural prerequisite to the <ahref="https://www.railstutorial.org/">>Ruby on Rails Tutorialem>a>, a book and video series that is one of the leading introductions to web development. <em>Learn Enough Rubyem> is also an excellent choice <em>afterem> the <em>Rails Tutorialem> for those who prefer to start with the latter first. p>
Listing 10.22:The core Palindrome Detector view.
views/palindrome.erb
<h1>Palindrome Detectorh1><p>This will be the palindrome detector.p>
Having stripped all the layout material from our pages, we’ll now create a file calledlayout.erbin theviewsdirectory that restores it:
Let’s start by filling it with the same content as the schematic HTML structure we saw in Listing 10.10, as seen in Listing 10.23.
Listing 10.23:Using an initial (incorrect) schematic layout.RED
views/layout.erb
<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample Apptitle> <linkrel="stylesheet"type="text/css"href="/stylesheets/main.css"> <linkhref="https://fonts.googleapis.com/css?family=Open+Sans:300,400"rel="stylesheet"> head> <body><ahref="/"class="header-logo"><imgsrc="/images/logo_b.png"alt="Learn Enough logo"> a> <divclass="container"><divclass="content">div> div> body> html>
As indicated in the caption to Listing 10.23, this layout breaks our test suite:
Listing 10.24:RED
$bundleexec耙test3 tests, 6 assertions, 3 failures, 0 errors, 0 skips
Theok?assertions in Listing 10.18 are passing, but theh1assertions are failing. This is because the site is now a bare layout, as shown inFigure 10.8.
Figure 10.8: The bare layout, with no content.
To get the tests to pass and restore our site to full functionality, all we need to do is replace the HTML comment
with some special Ruby code:
This is our first example ofembedded Ruby, which we’ll learn more about in Section 10.4. The special<%= ... %>notation arranges to evaluate the code represented by...and insert it into the site.
In this case, that code isyield, the keyword used in Section 5.4.1 to yield content to a block, but the truth is that I don’t know offhand exactly how this works or precisely why a block is involved. Indeed, I encourage you to think of<%= yield %>as meaning “special code that inserts the page content into a layout”, and not worry about the details. (If you do much Ruby web development, you’ll soon get used to it—the exact same code is used in Ruby on Rails application layouts.)
Making the replacement suggested above yields (heh) the layout shown in Listing 10.25.
Listing 10.25:Inserting content into the site layout.GREEN
views/layout.erb
<html><head><metacharset="utf-8"> <title>Learn Enough Ruby Sample Apptitle> <linkrel="stylesheet"type="text/css"href="/stylesheets/main.css"> <linkhref="https://fonts.googleapis.com/css?family=Open+Sans:300,400"rel="stylesheet"> head> <body><ahref="/"class="header-logo"><imgsrc="/images/logo_b.png"alt="Learn Enough logo">a> <divclass="container"><divclass="content"><%=yield%>div> div> body> html>
With that, our layout is working, the horrible repeated code has been eliminated, and our tests areGREEN:
Listing 10.26:GREEN
$bundleexec耙test3 tests, 6 assertions, 0 failures, 0 errors, 0 skips
A quick check in the browser confirms that things are working as expected (Figure 10.9).
Figure 10.9: Our Home page, now created using a layout.
By the way, it’s worth noting that we could have used a layout file called, say,views/page.erb, in which case we would have had to updateapp.rbwith an explicit hash option telling each page to use that file for the layout: