Skip to content

Commit

Permalink
SignUpUser raises error if validation fails
Browse files Browse the repository at this point in the history
These errors are rescued in the ApplicationController.

You may also want to extract the API-specific code in
ApplicationController (lines 4-8) into a separate ApiController that
your API controllers inherit from.  This is a good idea if you plan to
have a frontend Rails app, such as an admin portal.
  • Loading branch information
hchood committed Nov 15, 2015
1 parent 6559f93 commit fa19205
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 13 deletions.
4 changes: 4 additions & 0 deletions app/controllers/application_controller.rb
Expand Up @@ -2,4 +2,8 @@ class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :null_session

rescue_from ActiveRecord::RecordInvalid do |exception|
render json: { errors: exception.message }, status: :unprocessable_entity
end
end
8 changes: 1 addition & 7 deletions app/controllers/v1/users_controller.rb
@@ -1,13 +1,7 @@
class V1::UsersController < V1::ApplicationController
def create
user = SignUpUser.perform(user_params)

if user.save
render json: user, serializer: AuthenticationSerializer, root: :user
else
render json: { errors: user.errors.full_messages },
status: :unprocessable_entity
end
render json: user, serializer: AuthenticationSerializer, root: :user
end

private
Expand Down
1 change: 1 addition & 0 deletions app/services/sign_up_user.rb
Expand Up @@ -32,6 +32,7 @@ def password
def sign_up_user
user.tap do |user|
user.reset_token!
user.save!
end
end

Expand Down
2 changes: 1 addition & 1 deletion spec/requests/v1/users_requests_spec.rb
Expand Up @@ -33,7 +33,7 @@
post(users_url, user_attributes, accept_headers)

expect(response).to have_http_status :unprocessable_entity
expect(json_value_at_path('errors/0')).to eq 'Email has already been taken'
expect(json_value_at_path('errors')).to eq 'Validation failed: Email has already been taken'
end
end
end
Expand Down
9 changes: 4 additions & 5 deletions spec/services/sign_up_user_spec.rb
Expand Up @@ -18,13 +18,12 @@

context 'with invalid parameters' do
context 'such as a preexisting email' do
it 'does not persist the user' do
it 'raises an error' do
create(:user, email: email_attributes[:email])

result = SignUpUser.perform(email_attributes)

expect(result).to be_a User
expect(result).not_to be_persisted
expect {
SignUpUser.perform(email_attributes)
}.to raise_error ActiveRecord::RecordInvalid
end
end
end
Expand Down

0 comments on commit fa19205

Please sign in to comment.