Skip to content

Commit

Permalink
Merge pull request #4177 from RyanofWoods/ryanofwoods/fix-api-line-it…
Browse files Browse the repository at this point in the history
…ems-controller-create-error-handling

Fix Spree::Api:LineItemsController#create handling validation errors
  • Loading branch information
waiting-for-dev authored Aug 7, 2023
2 parents 834347e + 5946a34 commit 1a81736
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
17 changes: 8 additions & 9 deletions api/app/controllers/spree/api/line_items_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 6 additions & 0 deletions api/spec/requests/spree/api/line_items_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 1a81736

Please sign in to comment.