Add create method for users and corresponding controller tests.

This commit is contained in:
Stella Rouzi 2014-10-29 18:22:45 +02:00 committed by Stella
parent 2c98ba9711
commit 24712a0bd2
2 changed files with 67 additions and 0 deletions

View file

@ -6,6 +6,18 @@ module Admin
@user = User.new
end
def create
@user = User.new(user_params)
@user.password = Devise.friendly_token[0, 20]
@user.skip_confirmation!
if @user.save
redirect_to admin_users_path, notice: "User created. Name: #{@user.name}, email: #{@user.email}"
else
flash[:error] = "An error prohibited this user from being saved: #{@user.errors.full_messages.join('. ')}."
render :new
end
end
def index
@users = User.all
end
@ -33,5 +45,13 @@ module Admin
@user.destroy
redirect_to admin_users_path, notice: 'User got deleted'
end
private
# Only allow a trusted parameter "white list" through.
def user_params
# params.require(:user).permit(:email, :name, :affiliation, :biography)
params[:user]
end
end
end

View file

@ -50,4 +50,51 @@ describe Admin::UsersController do
end
end
describe 'GET #new' do
it 'assigns a new user to @user variable' do
get :new
expect(assigns(:user)).to be_a_new(User)
end
it 'renders the :new template' do
get :new
expect(response).to render_template :new
end
end
describe 'POST #create' do
context 'with valid attributes' do
it 'saves the user to the database' do
expected = expect do
post :create, user: { name: 'New User', email: 'newuser@osem.localhost' }
end
expected.to change { User.count }.by 1
end
it 'redirects to users#index' do
post :create, user: { name: 'New User', email: 'newuser@osem.localhost' }
expect(response).to redirect_to admin_users_path
end
it 'shows success message' do
post :create, user: { name: 'New User', email: 'newuser@osem.localhost' }
expect(flash[:notice]).to match("User created. Name: New User, email: newuser@osem.localhost")
end
end
context 'with invalid attributes' do
it 'does not save the user to the database' do
expected = expect do
post :create
end
expected.to_not change { User.count }
end
it 're-renders the new template' do
post :create
expect(response).to be_success
end
end
end
end