LoginSignup
6
2

More than 3 years have passed since last update.

Rails チュートリアル 10章 演習 10.4.1 でつまづいた点

Posted at

Railsチュートリアル 第10章 演習10.4.1について

Railsチュートリアル 第10章の演習10.4.1にで、adminユーザーをWeb経由で変更できないことを確認するテストを書きます。
一旦adminユーザーを変更可能にするため、

app/controllers/users_controller.rb
def user_params
      params.require(:user).permit(:admin,:name,:email,:password,:password_confirmation)
    end

このようにして:adminをの変更を許可しました。

テストは以下の通りに書きました。

test/controllers/users_controller_test.rb
  test "shuold not allow the admin attribute to be edited via the web" do
    log_in_as(@other_user)
    assert_not @other_user.admin?
    patch user_path(@other_user), params: {
                                    user: { password:              @other_user.password,
                                            password_confirmation: @other_user.password,
                                            admin: true } }
    assert_not @other_user.reload.admin?
  end

テストの結果は、REDを期待してましたが、、GREENになってしまいました。
adminの変更を許可したので、テストの最終行の

test/controllers/users_controller_test.rb
  assert_not @other_user.reload.admin?

の部分が通らない予定でしたが通ってしまいました。

必死にググってみてもなかなか原因がわからず、英語でググってみました。
すると僕と全く同じところでつまづいてる方の質問がstack overflowにありました。

どうやら原因は、テストで password と password_confirmation を @other_user を経由して呼び出そうとしていたところにあったようです。
パスワードは has_secure_password によって守られているので@other_userから呼び出すことはできないそうです。

なので、テストを以下のように変更しました。

test/controllers/users_controller_test.rb
test "shuold not allow the admin attribute to be edited via the web" do
    log_in_as(@other_user)
    assert_not @other_user.admin?
    patch user_path(@other_user), params: {
                                    user: { password:              "password",
                                            password_confirmation: "password",
                                            admin: true } }
    assert_not @other_user.reload.admin?
  end

直接パスワードを入力することによって(Railsチュートリアルではパスワードを"password"にしている)、admin を true に変更できました。
その結果、テストは期待通りにREDになりました。

最後に :adminをpermitから外して、テストがGREENになることを確認して終了です。

6
2
0

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
6
2