動態頁面
現在要幫「Home」、「Help」和「About」頁面加上標題:
Home | Ruby on Rails Tutorial Sample App
Help | Ruby on Rails Tutorial Sample App
About | Ruby on Rails Tutorial Sample App
使用完整的「Red -> Green -> Refactor」循環:先幫頁面的標題撰寫簡單的測試 (Red);然後分別在三個頁面中增加各自的標題 (Green),最後除去重複的內容 (Refactor)。
測試標題 (Red)
=> test/controllers/static_pages_controller_test.rb
require 'test_helper'
class StaticPagesControllerTest < ActionController::TestCase
test "should get home" do
..
..
assert_select "title", "Home | Ruby on Rails Tutorial Sample App"
end
test "should get help" do
..
..
assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
end
test "should get about" do
..
..
assert_select "title", "About | Ruby on Rails Tutorial Sample App"
end
end
執行測試,會顯示失敗 (Red):
$ rake test
3 tests, 6 assertions, 3 failures, 0 errors, 0 skips
增加頁面標題 (Green)、重構程式碼
為了通過測試,打開頁面檔案,分別加上各自的標題。這裡使用 provide 方法,讓標題可以帶入到 app/views/layouts/application.html.erb 的 yield
# app/views/static_pages/home.html.erb
<% provide(:title, "Home") %>
<h1>Sample App</h1>
<p>
This is the home page for the
<a href="http://www.railstutorial.org/">Ruby on Rails Tutorial</a>
sample application.
</p>
..
# app/views/static_pages/help.html.erb
<% provide(:title, "Help") %>
<h1>Help</h1>
<p>
Get help on the Ruby on Rails Tutorial at the
<a href="http://www.railstutorial.org/#help">Rails Tutorial help
section</a>.
To get help on this sample app, see the
<a href="http://www.railstutorial.org/book"><em>Ruby on Rails
Tutorial</em> book</a>.
</p>
..
# app/views/static_pages/About.html.erb
<% provide(:title, "About") %>
<h1>About</h1>
<p>
The <a href="http://www.railstutorial.org/"><em>Ruby on Rails
Tutorial</em></a> is a
<a href="http://www.railstutorial.org/book">book</a> and
<a href="http://screencasts.railstutorial.org/">screencast series</a>
to teach web development with
<a href="http://rubyonrails.org/">Ruby on Rails</a>.
This is the sample application for the tutorial.
</p>
=> app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
執行測試,可以通過了 (Green):
$ rake test
3 tests, 6 assertions, 0 failures, 0 errors, 0 skips
設定路由
把 Staticpages controller 的 action 「home」設成首頁:
=> config/routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
get 'static_pages/help'
get 'static_pages/about'
end
提交、合併、push、deploy
$ git add -A
$ git commit -m "Finish static pages"
$ git checkout master
$ git merge static-pages
$ git push
部署前,先執行測試是個好習慣
$ rake test
$ git push heroku