From f0732cc32a2833a1fe4bda7635f6877c5d09665d Mon Sep 17 00:00:00 2001 From: Eric Saupe Date: Mon, 19 Aug 2019 12:56:07 -0700 Subject: [PATCH] Raise exception if dividing by 0 While this should never happen it is possible to call this method and subsequently try to save a NaN value if the line_item has already been fully cancelled. --- core/app/models/spree/unit_cancel.rb | 5 ++++- core/spec/models/spree/unit_cancel_spec.rb | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/core/app/models/spree/unit_cancel.rb b/core/app/models/spree/unit_cancel.rb index d54c78ac614..38e0424d987 100644 --- a/core/app/models/spree/unit_cancel.rb +++ b/core/app/models/spree/unit_cancel.rb @@ -41,7 +41,10 @@ def compute_amount(line_item) private def weighted_line_item_amount(line_item) - line_item.total_before_tax / quantity_of_line_item(line_item) + quantity_of_line_item = quantity_of_line_item(line_item) + raise ZeroDivisionError, "Line Item does not have any inventory units available to cancel" if quantity_of_line_item.zero? + + line_item.total_before_tax / quantity_of_line_item end def quantity_of_line_item(line_item) diff --git a/core/spec/models/spree/unit_cancel_spec.rb b/core/spec/models/spree/unit_cancel_spec.rb index a5f52e21af6..139b8e2067d 100644 --- a/core/spec/models/spree/unit_cancel_spec.rb +++ b/core/spec/models/spree/unit_cancel_spec.rb @@ -48,6 +48,11 @@ it "divides the line item total by the uncanceled units size" do expect(subject).to eq(-10.0) end + + it "raises an error if dividing by 0" do + inventory_unit.cancel! + expect { subject }.to raise_error ZeroDivisionError, "Line Item does not have any inventory units available to cancel" + end end context "it is called with a line item that doesnt belong to the inventory unit" do