Profile micropost tests
新的已啟動使用者會直接被導向到自己的個人頁面,之前已經測試過這個行為了,這節要寫一個簡短的整合測試,檢查個人頁面的其他內容,首先,先建立一個整合測試文件:
$ rails generate integration_test users_profile
invoke test_unit
create test/integration/users_profile_test.rb
為了測試資料頁面有顯示 microposts,我們必須要關聯 fixture microposts 和 user。Rails 提供一種便利的方法,可以在 fixtures 中建立關聯:
orange:
content: "I just ate an orange!"
created_at: <%= 10.minutes.ago %>
user: michael
只要定義 user 值為 michael,Rails 就會把這篇 micropost 和指定的使用者關聯起來:
michael:
name: Michael Example
email: michael@example.com
.
.
.
要測試 microposts 分頁的話,可以透過 ERb 多產生一些 micropost fixtures:
<% 30.times do |n| %>
micropost_<%= n %>:
content: <%= Faker::Lorem.sentence(5) %>
created_at: <%= 42.days.ago %>
user: michael
<% end %>
現在就來更新 fixtures:
test/fixtures/microposts.yml
orange:
content: "I just ate an orange!"
created_at: <%= 10.minutes.ago %>
user: michael
tau_manifesto:
content: "Check out the @tauday site by @mhartl: http://tauday.com"
created_at: <%= 3.years.ago %>
user: michael
cat_video:
content: "Sad cats are sad: http://youtu.be/PKffm2uI4dk"
created_at: <%= 2.hours.ago %>
user: michael
most_recent:
content: "Writing a short test"
created_at: <%= Time.zone.now %>
user: michael
<% 30.times do |n| %>
micropost_<%= n %>:
content: <%= Faker::Lorem.sentence(5) %>
created_at: <%= 42.days.ago %>
user: michael
<% end %>
準備好測試的資料後,測試就變得很直覺:
- 瀏覽 user profile
- 檢查頁面標題
- 檢查使用者名稱
- 檢查 Gravatar
- 檢查 micropost 數量
- 檢查 microposts 分頁
以下是為整測試程式碼,注意,我們使用了 full_title 輔助方法來檢查頁面標題,所以要把 Application Helper module include 到測試裡面:
test/integration/users_profile_test.rb
require 'test_helper'
class UsersProfileTest < ActionDispatch::IntegrationTest
include ApplicationHelper
def setup
@user = users(:michael)
end
test "profile display" do
get user_path(@user)
assert_template 'users/show'
assert_select 'title', full_title(@user.name)
assert_select 'h1', text: @user.name
assert_select 'h1>img.gravatar'
assert_match @user.microposts.count.to_s, response.body
assert_select 'div.pagination'
@user.microposts.paginate(page: 1).each do |micropost|
assert_match micropost.content, response.body
end
end
end
檢查 micropost 數量時使用了 response.body,這個方法是用來回傳整個頁面的 HTML,如果我們只關心頁面中某處顯示的 microposts 數量,使用下面的程式碼找到匹配的內容即可:
assert_match @user.microposts.count.to_s, response.body
assert_match 沒有 assert_select 針對性強,使用 assert_match 不需要指定要尋找某個 HTML tag。
上述程式碼也在 assert_select 使用巢狀語法:
assert_select 'h1>img.gravatar'
這是要檢查 h1 tag 裡含有 .gravatar class 的 img tag。
現在執行測試應該會通過(Green):
$ bundle exec rake test