【83日目】【1日20分のRailsチュートリアル】【第8章】ログアウト機能を追加する
今日は「8.3 ログアウト」から。
8.3 ログアウト
ユーザーセッションを破棄するための有効なアクションをコントローラで作成するだけで済みます。
ユーザーセッションを破棄するlog_out
メソッドをSessionヘルパーに追加。
app/helpers/sessions_helper.rb
: # 現在のユーザーをログアウトする def log_out session.delete(:user_id) @current_user = nil end end
Sessionのdestroyアクションにてlog_out
メソッドを呼び出す。
app/controllers/sessions_controller.rb
def destroy log_out redirect_to root_url end
ログアウト機能をテストするために、リスト8.20のユーザーログインのテストに手順を若干追加します。
ログアウトを実施して、ルートURLにリダイレクトされること、ログイン用リンクが表示されること、ログアウト用リンクとプロフィールリンクが表示されないことを確認する。
test/integration/users_login_test.rb
: test "login with valid information followed by logout" do get login_path post login_path, session: { email: @user.email, password: 'password' } assert is_logged_in? assert_redirected_to @user follow_redirect! assert_template 'users/show' assert_select "a[href=?]", login_path, count: 0 assert_select "a[href=?]", logout_path assert_select "a[href=?]", user_path(@user) delete logout_path assert_not is_logged_in? assert_redirected_to root_url follow_redirect! assert_select "a[href=?]", login_path assert_select "a[href=?]", logout_path, count: 0 assert_select "a[href=?]", user_path(@user), count: 0 end end
テスト実行して問題ないことを確認。
$ bundle exec rake test 24 tests, 61 assertions, 0 failures, 0 errors, 0 skips
ログアウト処理はセッションからユーザー情報削除するのがメインだしそんなに難しくない印象。
今日の作業時間は【17分】。
次は「8.4 [このアカウント設定を保存する]」から。