Respond with errors if image upload fails

This commit is contained in:
Maikel Linke
2022-06-14 15:06:17 +10:00
parent 6b733ad7e2
commit 5f11b6a650
2 changed files with 19 additions and 3 deletions

View File

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

View File

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