各ページのビューにprovideを記述
<% provide(:title, "Home") %>
<h1>Sample App</h1>
appilication.htmlのtitleにyieldを記述
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
</head>
ページタイトルに対するテスト
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end
test "should get home" do
get static_pages_home_url
assert_response :success
assert_select "title", "Home | #{@base_title}"
end
assert_selectを使って、titlesセレクタがページタイトルと一致することを確認する。
ページタイトルの重複部分はsetup内の変数@base_titleに入れておく。
~ここから4章~
full_titleヘルパーを作成
rootであるhomeビューでは、アプリケーション名のみをタイトルに表示したい。
そのため、homeビューではprovideは不要である。
しかし、この場合タイトルが「 | Ruby on Rails Tutorial Sample App」となり、余計な|が入る。
これを修正するためにページタイトルを返すfull_titleヘルパーを作成する。
module ApplicationHelper
# ページごとの完全なタイトルを返す。
def full_title(page_title = "")
base_title = "Ruby on Rails Tutorial Sample App"
if page_title.empty?
base_title
else
page_title + " | " + base_title
end
end
end
<html>
<head>
<title><%= full_title(yield(:title)) %></title>
</head>
変数page_titleの初期値を空にしておき、provideからくる引数yield(:title)が与えられなければ、base_titleのみを表示する。
与えられれば、|を追加して、完全なタイトルを表示する。
(ちなみに、empty?メソッドの末尾の?は、論理値を返すメソッドであることを意味する)
homeビューからはprovideを消しておく。
<h1>Sample App</h1>
「home」という文字はもうタイトルには無いので、テストを修正しておく。
test "should get home" do
get static_pages_home_url
assert_response :success
assert_select "title", @base_title
end
〜ここから5章〜
full_titleヘルパーのテスト
タイトルに誤字などがないか、正しく機能しているかどうかをテストする。
applicationヘルパーにあるfull_titleヘルパーはそのままではテストで使えないので、includeを使ってテストで使えるようにする。
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
include ApplicationHelper
end
require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
test "full title helper" do
assert_equal full_title, "Ruby on Rails Tutorial Sample App"
assert_equal full_title("Help"), "Help | Ruby on Rails Tutorial Sample App"
end
end
asseet_equalは第一引数と第二引数が等しいかどうかを確認するために使用する。
ところで、test/helpers/application_helper_test.rbは自動で生成されないようである。