Users index test
接下來要幫 index 頁面寫個簡單的測試。計畫是:
- 登入
- 瀏覽
index - 檢查第一頁的使用者是否顯示
- 檢查分頁是否顯示
但首先我們必須在 test 資料庫裡準備足夠的使用者來進行測試,起碼要超過 30 個使用者。
我們之前在 fixture 裡面手動增加第二個使用者,但如果要手動增加到 30 個也太累了。不過由於 fixture 支援 ERb,所以我們可以用以下方式增加使用者:(另外也增加一組其他名稱的使用者,之後會用到)
test/fixtures/users.yml
michael:
name: Michael Example
email: michael@example.com
password_digest: <%= User.digest('password') %>
archer:
name: Sterling Archer
email: duchess@example.gov
password_digest: <%= User.digest('password') %>
lana:
name: Lana Kane
email: hands@example.gov
password_digest: <%= User.digest('password') %>
malory:
name: Malory Archer
email: boss@example.gov
password_digest: <%= User.digest('password') %>
<% 30.times do |n| %>
user_<%= n %>:
name: <%= "User #{n}" %>
email: <%= "user-#{n}@example.com" %>
password_digest: <%= User.digest('password') %>
<% end %>
準備好 test 資料庫用的使用者之後,就可以建立測試檔案了:
$ rails generate integration_test users_index
invoke test_unit
create test/integration/users_index_test.rb
這個測試會檢查 div.pagination 元素是否存在以及第一頁的使用者是否有顯示:
test/integration/users_index_test.rb
require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "index including pagination" do
log_in_as(@user)
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
User.paginate(page: 1).each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name
end
end
end
執行測試應該會通過(Green):
$ bundle exec rake test