diff --git a/app/controllers/api/application_controller.rb b/app/controllers/api/application_controller.rb index b8de05d..0bea5bc 100644 --- a/app/controllers/api/application_controller.rb +++ b/app/controllers/api/application_controller.rb @@ -1,11 +1,17 @@ module API class ApplicationController < ::ApplicationController + rescue_from ActiveRecord::RecordNotFound, with: :not_found + skip_before_filter :verify_authenticity_token skip_before_filter :authenticate!, only: :cor_preflight before_filter :cor_filter before_filter :json_filter! + def not_found + head :not_found + end + def cor_filter headers['Access-Control-Allow-Origin'] = request.headers['Origin'] ? request.headers['Origin'] : @@ -31,7 +37,9 @@ module API end def json_filter! - head :not_acceptable if request.format != :json + if request.format != :json + head :not_acceptable, content_type: 'application/json' + end end end end diff --git a/config/routes.rb b/config/routes.rb index dd5ae1a..70f0e84 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -8,6 +8,7 @@ Rails.application.routes.draw do resources :sessions, only: :create resources :sounds, only: :show resources :tracks, only: :index + match '*all', to: 'application#not_found', via: :all end resources :playlists diff --git a/spec/integration/api/application_spec.rb b/spec/integration/api/application_spec.rb index 8c7d26b..7f69dad 100644 --- a/spec/integration/api/application_spec.rb +++ b/spec/integration/api/application_spec.rb @@ -15,6 +15,21 @@ describe 'API application' do it 'responds with a 406 when request format is not JSON' do get api_ping_path, format: :xml expect(response.status).to be 406 + expect(response.content_type).to eq :json + expect(response.body).to be_empty + end + end + + describe 'not found' do + it 'responds with a 404 when route does not exist' do + get '/api/not_found', format: :json + expect(response.status).to be 404 + expect(response.body).to be_empty + end + + it 'responds with a 404 when a resource (AR) was not found' do + get api_playlist_path(id: 1), format: :json + expect(response.status).to be 404 expect(response.body).to be_empty end end