From 332bf8f1dfd37f3bfb44103908da2775a6693da0 Mon Sep 17 00:00:00 2001 From: Michael Ball Date: Mon, 8 Mar 2021 20:19:57 -0800 Subject: [PATCH] Support the ability for admins to delete users --- app/controllers/admin/users_controller.rb | 12 ++++++++---- app/views/admin/users/show.html.haml | 4 +++- spec/controllers/admin/users_controller_spec.rb | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 0cfdfd82..2eb2032a 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -66,10 +66,14 @@ module Admin def edit; end - def delete - @user.destroy! - flash[:notice] = "User #{@user.id} (#{@user.emai}) successfully deleted." - redirect_to admin_users_path + def destroy + if @user.destroy + redirect_to admin_users_path, + notice: "User #{@user.id} (#{@user.email}) deleted." + else + redirect_to admin_users_path, + error: "User #{@user.id} (#{@user.emai}) could not be deleted. #{@user.full_messages.join(',')}" + end end private diff --git a/app/views/admin/users/show.html.haml b/app/views/admin/users/show.html.haml index b90e72d9..c0a8f1fb 100644 --- a/app/views/admin/users/show.html.haml +++ b/app/views/admin/users/show.html.haml @@ -12,8 +12,10 @@ .tab-content #user-info-content.tab-pane{class: "#{'active' unless params[:tab] == 'submissions-content'}"} - if can? :edit, @user - .pull-right + .pull-right.btn-group = link_to 'Edit', edit_admin_user_path(@user), class: 'btn btn-primary' + = link_to 'Delete', admin_user_path(@user),method: :delete, class: 'btn btn-danger', + data: {confirm: "Are you sure?"} %table.table - @show_attributes.each do |attr| %tr diff --git a/spec/controllers/admin/users_controller_spec.rb b/spec/controllers/admin/users_controller_spec.rb index 51dfb04c..c3d29b81 100644 --- a/spec/controllers/admin/users_controller_spec.rb +++ b/spec/controllers/admin/users_controller_spec.rb @@ -103,4 +103,21 @@ describe Admin::UsersController do end end end + + describe 'DELETE #destroy' do + before do + delete :destroy, params: { id: user.id } + end + it 'redirects to admin users index path' do + expect(response).to redirect_to admin_users_path + end + + it 'shows success message in flash notice' do + expect(flash[:notice]).to match("User #{user.id} (#{user.email}) deleted.") + end + + it 'deletes the user' do + expect { user.reload }.to raise_error(ActiveRecord::RecordNotFound) + end + end end