Merge branch 'api-error-handling'

This commit is contained in:
Thibault Jouan 2015-05-01 22:17:44 +00:00
commit b543afbfff
3 changed files with 25 additions and 1 deletions

View File

@ -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

View File

@ -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

View File

@ -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