From 5f11b6a650d0e6e052e3067becfed1bf2850aed1 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Tue, 14 Jun 2022 15:06:17 +1000 Subject: [PATCH] Respond with errors if image upload fails --- app/controllers/api/v0/product_images_controller.rb | 9 ++++++--- .../api/v0/product_images_controller_spec.rb | 13 +++++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/controllers/api/v0/product_images_controller.rb b/app/controllers/api/v0/product_images_controller.rb index b752755a10..1df2664224 100644 --- a/app/controllers/api/v0/product_images_controller.rb +++ b/app/controllers/api/v0/product_images_controller.rb @@ -16,9 +16,12 @@ module Api success_status = image.persisted? ? :ok : :created - image.update(attachment: params[:file]) - - render json: image, serializer: ImageSerializer, status: success_status + if image.update(attachment: params[:file]) + render json: image, serializer: ImageSerializer, status: success_status + else + error_json = { errors: image.errors.full_messages } + render json: error_json, status: :unprocessable_entity + end end end end diff --git a/spec/controllers/api/v0/product_images_controller_spec.rb b/spec/controllers/api/v0/product_images_controller_spec.rb index d4b5f93fba..c40785ba2c 100644 --- a/spec/controllers/api/v0/product_images_controller_spec.rb +++ b/spec/controllers/api/v0/product_images_controller_spec.rb @@ -9,6 +9,8 @@ describe Api::V0::ProductImagesController, type: :controller do describe "uploading an image" do let(:image) { Rack::Test::UploadedFile.new(black_logo_file, 'image/png') } + let(:pdf) { Rack::Test::UploadedFile.new(pdf_path, 'application/pdf') } + let(:pdf_path) { Rails.root.join("public/Terms-of-service.pdf") } let(:product_without_image) { create(:product) } let(:product_with_image) { create(:product_with_image) } let(:current_api_user) { create(:admin_user) } @@ -34,5 +36,16 @@ describe Api::V0::ProductImagesController, type: :controller do expect(response.status).to eq 200 expect(product_with_image.images.first.id).to eq json_response['id'] end + + it "reports errors when saving fails" do + post :update_product_image, xhr: true, params: { + product_id: product_without_image.id, file: pdf, use_route: :product_images + } + + expect(response.status).to eq 422 + expect(product_without_image.images.count).to eq 0 + expect(json_response["id"]).to eq nil + expect(json_response["errors"]).to include "Attachment has an invalid content type" + end end end