Skip to content

How to add User Accounts for users to administer their personal accounts

crmaxx edited this page · 9 revisions

Create Account resource

ActiveAdmin.register AdminUser, as: 'Account' do
  actions :edit, :update

  menu parent: 'Users'

  controller do
    def redirect_to_edit
      redirect_to edit_admin_account_path(current_admin_user), :flash => flash
    end

    alias_method :index, :redirect_to_edit
    alias_method :show,  :redirect_to_edit
  end

  form do |f|
    f.inputs do
      f.input :email
      f.input :password
      f.input :password_confirmation
    end

    f.actions
  end
end

And created some tests (RSpec)

# /spec/controllers/admin/accounts_spec.rb
require 'spec_helper'

describe Admin::AccountsController do
  let(:user) { mock_model(User) }

  before do
    controller.should_receive(:current_admin_user).and_return user
    controller.should_receive(:authenticate_user!).and_return true
  end

  context '#index & #show' do
    after do
      response.should redirect_to action: :edit, id: user.id
    end

    it 'should redirect to #edit' do
      get :index
    end

    it 'should redirect to #edit' do
      get :show, id: user.id
    end
  end
end
# /spec/requests/admin/accounts_spec.rb
require 'spec_helper'

describe 'Admin::AcccountsController' do
  let(:user) { Factory :user }
  before { sign_in user }

  it 'should edit users account and force user to sign in with new credentials' do
    visit edit_admin_account_path user

    new_email, new_password = 'my@email.com', 'password'

    within 'form#edit_account' do
      fill_in 'account_email', with: new_email
      fill_in 'account_password', with: new_password
      fill_in 'account_password_confirmation', with: new_password

      click_button 'Update User'
    end

    current_path.should == new_user_session_path

    within 'form#session_new' do
      fill_in 'user_email', with: new_email
      fill_in 'user_password', with: new_password

      click_button 'Login'
    end

    current_path.should == edit_admin_account_path(user)
  end
end
# /spec/support/devise.rb
RSpec.configure do |config|
  config.include Warden::Test::Helpers

  config.before(:all) do
    Warden.test_mode!
  end

  config.after(:all) do
    Warden.test_reset!
  end
end

def sign_in(user)
  login_as user
end
Something went wrong with that request. Please try again.