0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

0
Last updated at Posted at 2019-11-05

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メソッドを使って、当該ブロックの処理の前後でユーザー数が変化しないことを確認している。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?