Skip to content

Commit

Permalink
feat: user create
Browse files Browse the repository at this point in the history
  • Loading branch information
noahdurbin committed Aug 22, 2024
1 parent 3e280ca commit 6c97cfb
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
2 changes: 1 addition & 1 deletion app/controllers/api/v1/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ def create
if user.save
render json: UserSerializer.new(user), status: :created
else
render json: ErrorSerializer.new(user.errors), status: :unprocessable_entity
render json: ErrorSerializer.new(user, :unprocessable_entity).serialize, status: :unprocessable_entity
end
end

Expand Down
23 changes: 23 additions & 0 deletions app/serializers/error_serializer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
class ErrorSerializer
def initialize(object, status_code)
@object = object
@status_code = status_code.to_s
end

def serialize
{
errors: format_errors
}
end

private

def format_errors
@object.errors.full_messages.map do |message|
{
status: @status_code,
message:
}
end
end
end
23 changes: 17 additions & 6 deletions spec/requests/api/v1/user_request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,38 @@

RSpec.describe 'User requests', type: :request do
describe 'POST /users' do
it 'creates a new user - happy path' do
it 'creates a new user' do
user_params = { email: '[email protected]', password: 'password', password_confirmation: 'password' }

post '/api/v1/users', params: { user: user_params }
post '/api/v1/users', params: user_params

expect(response).to have_http_status(:created)

user = JSON.parse(response.body, symbolize_names: true)
expect(user[:data][:attributes][:email]).to eq(user_params[:email])
end

it 'requires all fields - sad path' do
user_params = { email: '[email protected]', password: '' }
it 'requires all fields' do
user_params = { email: '[email protected]', password: '', password_confirmation: 'password' }

post '/api/v1/users', params: { user: user_params }
post '/api/v1/users', params: user_params

expect(response).to have_http_status(:unprocessable_entity)
error = JSON.parse(response.body, symbolize_names: true)

expect(error[:errors].first[:message]).to eq("Password can't be blank")
end

it 'requires password to match password confirmation' do
user_params = { email: '[email protected]', password: 'wordpass', password_confirmation: 'password' }

post '/api/v1/users', params: user_params

expect(response).to have_http_status(:unprocessable_entity)

error = JSON.parse(response.body, symbolize_names: true)

expect(error.first[:status]).to eq("Password can't be blank")
expect(error[:errors].first[:message]).to eq("Password confirmation doesn't match Password")
end
end
end

0 comments on commit 6c97cfb

Please sign in to comment.