Skip to content

Commit

Permalink
Fix Spree::Api:LineItemsController#create handling validation errors
Browse files Browse the repository at this point in the history
Before, #create was expecting that the LineItem instance would have
errors if failed to be created due to validation errors. However,
 #add actually raises ActiveRecord::RecordInvalid: Validation failed,
so this endpoint could have never handled validation errors correctly.
  • Loading branch information
RyanofWoods committed Jul 21, 2023
1 parent afa4d89 commit 5946a34
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 5946a34

Please sign in to comment.