【179日目】【1日20分のRailsチュートリアル】【第12章】フォロー/フォロー解除をテストする
今日は「12.2.6 フォローをテストする」から。
12.2.6 フォローをテストする
ユーザーのフォローに対するテストでは、 /relationshipsに対してPOSTリクエストを送り、フォローされたユーザーが1人増えたことをチェックします。
Ajaxでのリクエスト発行もテストで書けるのか…!xhr (XmlHttpRequest) っていうメソッド使うらしい。
これらのテストをまとめた結果を、リスト12.39に示します。
普通のHTTPリクエストとAjaxでのPOST/DELETEリクエストをテストする。
リクエスト発行後、フォローされたユーザーが1人増えているか、フォローしているユーザーが1人減っているかを見る。
ふむ、結構シンプルなテスト。
test/integration/following_test.rb
def setup @user = users(:michael) @other = users(:archer) log_in_as(@user) end : test "should follow a user the standard way" do assert_difference '@user.following.count', 1 do post relationships_path, followed_id: @other.id end end test "should follow a user with Ajax" do assert_difference '@user.following.count', 1 do xhr :post, relationships_path, followed_id: @other.id end end test "should unfollow a user the standard way" do @user.follow(@other) relationship = @user.active_relationships.find_by(followed_id: @other.id) assert_difference '@user.following.count', -1 do delete relationship_path(relationship) end end test "should unfollow a user with Ajax" do @user.follow(@other) relationship = @user.active_relationships.find_by(followed_id: @other.id) assert_difference '@user.following.count', -1 do xhr :delete, relationship_path(relationship) end end
特に問題なくテスト通りました。
$ bundle exec rake test 73 tests, 333 assertions, 0 failures, 0 errors, 0 skips
今日の学習時間は【13分】。
次は「12.3 ステータスフィード」から。