From b29983ac602d2e108df59bac8e19ad364942cfb4 Mon Sep 17 00:00:00 2001 From: luisramos0 Date: Wed, 31 Jul 2019 22:00:41 +0100 Subject: [PATCH] Add AMS versions of the error responses in api/base_controller and cover not_found case with a unit test --- app/controllers/api/base_controller.rb | 22 ++++++++++++++++++++ spec/controllers/api/base_controller_spec.rb | 10 ++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/app/controllers/api/base_controller.rb b/app/controllers/api/base_controller.rb index 8a1b3e4b02..668bb6f065 100644 --- a/app/controllers/api/base_controller.rb +++ b/app/controllers/api/base_controller.rb @@ -30,5 +30,27 @@ module Api def requires_authentication? false end + + def invalid_resource!(resource) + @resource = resource + render(json: { error: I18n.t(:invalid_resource, scope: "spree.api"), + errors: @resource.errors }, + status: :unprocessable_entity) + end + + def invalid_api_key + render(json: { error: I18n.t(:invalid_api_key, key: api_key, scope: "spree.api") }, + status: :unauthorized) && return + end + + def unauthorized + render(json: { error: I18n.t(:unauthorized, scope: "spree.api") }, + status: :unauthorized) && return + end + + def not_found + render(json: { error: I18n.t(:resource_not_found, scope: "spree.api") }, + status: :not_found) && return + end end end diff --git a/spec/controllers/api/base_controller_spec.rb b/spec/controllers/api/base_controller_spec.rb index 6d0c88f044..df44fb5d8e 100644 --- a/spec/controllers/api/base_controller_spec.rb +++ b/spec/controllers/api/base_controller_spec.rb @@ -50,10 +50,18 @@ describe Api::BaseController do it 'handles exceptions' do expect(subject).to receive(:authenticate_user).and_return(true) expect(subject).to receive(:index).and_raise(Exception.new("no joy")) - get :index, token: "fake_key" + get :index expect(json_response).to eq( "exception" => "no joy" ) end + it 'handles record not found' do + expect(subject).to receive(:authenticate_user).and_return(true) + expect(subject).to receive(:index).and_raise(ActiveRecord::RecordNotFound.new) + get :index + expect(json_response).to eq( "error" => "The resource you were looking for could not be found." ) + expect(response.status).to eq(404) + end + it "maps symantec keys to nested_attributes keys" do klass = double(nested_attributes_options: { line_items: {}, bill_address: {} })