diff --git a/api/app/controllers/spree/api/line_items_controller.rb b/api/app/controllers/spree/api/line_items_controller.rb index e8ee1f0f01b..e6b6a43bbe1 100644 --- a/api/app/controllers/spree/api/line_items_controller.rb +++ b/api/app/controllers/spree/api/line_items_controller.rb @@ -11,16 +11,15 @@ def new def create variant = Spree::Variant.find(params[:line_item][:variant_id]) - @line_item = @order.contents.add( - variant, - params[:line_item][:quantity] || 1, - options: line_item_params[:options].to_h - ) - - if @line_item.errors.empty? + begin + @line_item = @order.contents.add( + variant, + params[:line_item][:quantity] || 1, + options: line_item_params[:options].to_h + ) respond_with(@line_item, status: 201, default_template: :show) - else - invalid_resource!(@line_item) + rescue ActiveRecord::RecordInvalid => error + invalid_resource!(error.record) end end diff --git a/api/spec/requests/spree/api/line_items_spec.rb b/api/spec/requests/spree/api/line_items_spec.rb index bb092fa1171..9db68f36e7d 100644 --- a/api/spec/requests/spree/api/line_items_spec.rb +++ b/api/spec/requests/spree/api/line_items_spec.rb @@ -95,6 +95,12 @@ module Spree::Api expect(response.status).to eq(201) end + it '#create calls #invalid_resource! if adding a line item fails validation' do + allow_any_instance_of(Spree::LineItem).to receive(:valid?).and_return(false) + expect_any_instance_of(Spree::Api::BaseController).to receive(:invalid_resource!).once + post spree.api_order_line_items_path(order), params: { line_item: { variant_id: product.master.to_param, quantity: 1 } } + end + it "default quantity to 1 if none is given" do post spree.api_order_line_items_path(order), params: { line_item: { variant_id: product.master.to_param } } expect(response.status).to eq(201)