From a7c970054cd5e07ab8051fed88d1a9f1be4059ee Mon Sep 17 00:00:00 2001 From: luisramos0 Date: Wed, 12 Jun 2019 16:33:11 +0100 Subject: [PATCH] Add rescue in product controller create action to avoid server error and send appropriate error message to client when product image upload fails --- .../admin/products_controller_decorator.rb | 4 ++++ config/locales/en.yml | 2 ++ .../spree/admin/products_controller_spec.rb | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/app/controllers/spree/admin/products_controller_decorator.rb b/app/controllers/spree/admin/products_controller_decorator.rb index ed3f8039df..53638b9a1e 100644 --- a/app/controllers/spree/admin/products_controller_decorator.rb +++ b/app/controllers/spree/admin/products_controller_decorator.rb @@ -33,6 +33,10 @@ Spree::Admin::ProductsController.class_eval do delete_stock_params_and_set_after do super end + rescue Paperclip::Errors::NotIdentifiedByImageMagickError + invoke_callbacks(:create, :fails) + @object.errors.add(:base, t('spree.admin.products.image_upload_error')) + respond_with(@object) end def update diff --git a/config/locales/en.yml b/config/locales/en.yml index bf914a13ea..8c49809815 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -3011,6 +3011,8 @@ See the %{link} to find out more about %{sitename}'s features and to start using error_saving_payment: Error saving payment submitting_payment: Submitting payment... products: + image_upload_error: "The product image was not recognised. Please upload an image in PNG or JPG format." + new: title: 'New Product' unit_name_placeholder: 'eg. bunches' diff --git a/spec/controllers/spree/admin/products_controller_spec.rb b/spec/controllers/spree/admin/products_controller_spec.rb index 1f6356b98b..d630237742 100644 --- a/spec/controllers/spree/admin/products_controller_spec.rb +++ b/spec/controllers/spree/admin/products_controller_spec.rb @@ -147,6 +147,25 @@ describe Spree::Admin::ProductsController, type: :controller do spree_post :create, product: product_attrs, button: 'add_another' expect(response).to redirect_to spree.new_admin_product_path end + + describe "when user uploads an image in an unsupported format" do + it "does not throw an exception" do + product_image = ActionDispatch::Http::UploadedFile.new({ + :filename => 'unsupported_image_format.exr', + :content_type => 'application/octet-stream', + :tempfile => Tempfile.new('unsupported_image_format.exr') + }) + product_attrs_with_image = product_attrs.merge( + images_attributes: { + '0' => { attachment: product_image } + }) + + expect do + spree_put :create, product: product_attrs_with_image + end.not_to raise_error Paperclip::Errors::NotIdentifiedByImageMagickError + expect(response.status).to eq 200 + end + end end describe "updating" do