Ruby on Rails チュートリアル 第10章 10.4.3 ユーザー削除のテスト


10.4.3 ユーザー削除のテスト

10.4.3以前の部分で作成したユーザーを削除する機能のテストを実装していく。
まず。テストで使用可能なユーザーのデータを書き込む test/fixtures/users.yml ファイルにおいて以下のように、サンプルユーザーの一人に管理者属性を付加する。こうすることでテストにおいても管理者権限を持つユーザーが削除を行えるようにする。

test/fixtures/users.yml

michael:
  name: Michael Example
  email: michael@example.com
  password_digest: <%= User.digest('password') %>
  admin: true

次に、ユーザー削除に関するテストをUsersコントローラーのアクション単位で実装するため、テストファイルにおいてdeleteリクエストを発行しdestroyアクションを動作させる。

test/controllers/users_controller_test.rb

require 'test_helper'

class UsersControllerTest < ActionDispatch::IntegrationTest

  def setup
    @user       = users(:michael)
    @other_user = users(:archer)
  end
  .
  .
  .
  test "should redirect destroy when not logged in" do
    assert_no_difference 'User.count' do
      delete user_path(@user)
    end
    assert_redirected_to login_url
  end

  test "should redirect destroy when logged in as a non-admin" do
    log_in_as(@other_user)
    assert_no_difference 'User.count' do
      delete user_path(@user)
    end
    assert_redirected_to root_url
  end
end

このファイルのテストでは、assert_no_differenceメソッドを使って、当該ブロックの処理の前後でユーザー数が変化しないことを確認している。