Merge pull request #27 from turniere/ticket/TURNIERE-142

Render error response for invalid parameters
This commit is contained in:
Daniel Schädler 2019-04-16 14:07:14 +02:00 committed by GitHub
commit 55ffdba1b6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 0 deletions

View File

@ -5,6 +5,10 @@ class ApplicationController < ActionController::API
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from ActionController::ParameterMissing do |e|
render json: { error: e.message }, status: :bad_request
end
protected
def configure_permitted_parameters

View File

@ -4,6 +4,7 @@ class TournamentsController < ApplicationController
before_action :set_tournament, only: %i[show update destroy]
before_action :authenticate_user!, only: %i[create update destroy]
before_action -> { require_owner! @tournament.owner }, only: %i[update destroy]
before_action :validate_create_params, only: %i[create]
rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_error
# GET /tournaments
@ -71,4 +72,11 @@ class TournamentsController < ApplicationController
def tournament_params
params.slice(:name, :description, :public, :teams).permit!
end
def validate_create_params
teams = params['teams']
return if teams.is_a?(Array) && teams.reject { |t| t.is_a? ActionController::Parameters }.count.zero?
render json: { error: 'Invalid teams array' }, status: :unprocessable_entity
end
end

View File

@ -142,6 +142,13 @@ RSpec.describe TournamentsController, type: :controller do
end.to change(Team, :count).by(data[:teams].count)
end
end
context 'with invalid parameters' do
it 'renders an unprocessable entity response' do
put :create, params: { teams: [1, 2, 3] }
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
end