Layout link tests
現在要利用整合測試(integration test)來測試網站的連結有沒有作用。
先建立一個「site_layout」整合測試的檔案:
$ rails generate integration_test site_layout
invoke test_unit
create test/integration/site_layout_test.rb
Rails 會自動幫你建在 test/integration/ 目錄底下,檔名後面也會幫你加上 _test。
測試的流程,檢查 HTML 結構:
- 瀏覽首頁(root path)
- 確認使用正確的 template
- 檢查指向 Home、Help、About、Contact 頁面的網址是否正確
test/integration/site_layout_test.rb
require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
test "layout links" do
get root_path
assert_template 'static_pages/home'
assert_select "a[href=?]", root_path, count: 2
assert_select "a[href=?]", help_path
assert_select "a[href=?]", about_path
assert_select "a[href=?]", contact_path
end
end
assert_template 方法是用來檢查 Home 是否使用正確的 template。
assert_select "a[href=?]", about_path 指定了 a tag 和屬性 href,檢查有沒有指定的連結。Rails 會自動把 ? 換成 about_path,檢查有沒有下面的 HTML 元素:
<a href="/about">...</a>
而這一行,是檢查頁面中有沒有兩個指向 Home 的連結(Logo 一個,導覽列一個):
assert_select "a[href=?]", root_path, count: 2
接著就可以來測試(Green),這行指定只要執行整合測試:
$ bundle exec rake test:integration
然後再執行所有測試,確認都成功(Green):
$ bundle exec rake test
assert_select 的更多用法:
| Code | Matching HTML |
|---|---|
| assert_select "div" | foobar |
| assert_select "div", "foobar" | foobar |
| assert_select "div.nav" | |
| assert_select "div#profile" | foobar |
| assert_select "div[name=yo]" | hey |
| assert_select "a[href=?]", ’/’, count: 1 | foo |
| assert_select "a[href=?]", ’/’, text: "foo" | foo |
最好只測試不會經常變動的 HTML 元素。