【176日目】【1日20分のRailsチュートリアル】【第12章】フォローしているユーザー/フォロワーページの統合テストを作成する
今日は「12.2.3「フォローしているユーザー」ページと「フォロワー」ページ」の統合テストを書くところから。
12.2.3「フォローしているユーザー」ページと「フォロワー」ページ
フォロー一覧もフォロワー一覧も動くようになったので、この振る舞いを検証するための2つの統合テストを書いていきましょう。
(中略)
したがって今回は、正しい数が表示されているかどうかと、正しいURLが表示されているかどうかの2つのテストを書きます。
網羅的なテストは壊れやすいそうなので最低限を確認する統合テストを作成する。
まずは統合テストを生成。
$ rails generate integration_test following invoke test_unit create test/integration/following_test.rb
リレーションシップ用のfixtureにテストデータを追加すると、リスト12.27のようになります。
ユーザーidでも関連付けできるけど、ユーザー名でも関連付けできる、ってことかな…。
ユーザーidで書くより分かりやすいね。
test/fixtures/relationships.yml
one: follower: michael followed: lana two: follower: michael followed: mallory three: follower: lana followed: michael four: follower: archer followed: michael
正しい数かどうかを確認するために、assert_matchメソッド (リスト11.27) を使ってプロフィール画面のマイクロポスト数をテストします。さらに、正しいURLかどうかをテストするコードも加えると、リスト12.28のようになります。
フォローしているユーザーのページとフォロワーページそれぞれについて、
・フォローしているユーザー/フォロワーの数が表示されていること
・フォローしているユーザー/フォロワーのユーザーページへのリンクがあること
を確認する感じかな。
test/integration/following_test.rb
require 'test_helper' class FollowingTest < ActionDispatch::IntegrationTest def setup @user = users(:michael) log_in_as(@user) end test "following page" do get following_user_path(@user) assert_not @user.following.empty? assert_match @user.following.count.to_s, response.body @user.following.each do |user| assert_select "a[href=?]", user_path(user) end end test "followers page" do get followers_user_path(@user) assert_not @user.followers.empty? assert_match @user.followers.count.to_s, response.body @user.followers.each do |user| assert_select "a[href=?]", user_path(user) end end end
テストを実行して問題ないことを確認。
$ bundle exec rake test 67 tests, 325 assertions, 0 failures, 0 errors, 0 skips
今日の学習時間は【18分】。
次は「12.2.4 [フォローする] ボタン (標準的な方法)」から。