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

【RSpec】current_userを削除するdestroyアクションのテスト

Posted at

はじめに

  • current_userを削除するdestroyアクションを実装し、それに対するRSpec(request spec)でのテスト方法を備忘含めまとめます

コントローラーのdestroyアクション

def destroy
    current_user.destroy
    reset_session
    flash[:notice] = "アカウントを削除しました"
    redirect_to root_path
end

テストで確認したいこと

  • ログイン中のアカウントが削除されること
  • 削除後、セッションが消えること
  • 正しいパスへリダイレクトすること
  • フラッシュメッセージが表示すること

テストコード

また読みやすく、再現性と保守性の高いテストになるようにAAAを意識して記述しました。

RSpec.describe "Users", type: :request do
    # Arrange(準備)
    let!(:user) { create(:user) } # ユーザーの作成

    before do # ログイン状態の作成
        post "/login", params{
            session: {
                email: user.email,
                password: "password"
            }
        }
    end

    describe "DELETE /user" do
        context "ログイン中のアカウントの削除をした時" do
            it "正常に削除されること" do
                # Act(実行)
                expect{
                    delete withdrow_user_path
                }.to change(User, :count).by(-1)
                
                # Assert(検証)
                expect(session[:user_id]).to be_nil
                expect(response).to redirect_to root_path
                follow_redirect!
                expect(response.body).to include("アカウントを削除しました")
                expect(response).to have_http_status(:ok)
            end
        end
    end

まとめ

  • delete メソッドで current_user の削除をテストするにはログイン状態の再現が必要
  • 削除後の状態(副作用)も合わせてテストすることで、意図した挙動が担保される
  • AAAパターンを意識することで構造化されたテストが書けます

参考にした記事

2
0
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
2
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?