Ensure variants don't end up with invalid data when a product's variant_unit is changed

Fixes an issue where a product's variant_unit value is changed from "weight" to "items" and some of the product's variants can be left in an invalid state, which in turn breaks cloning of order cycles (with fatal errors).
This commit is contained in:
Matt-Yorkley
2020-11-11 20:24:21 +00:00
parent 6114dfb4ef
commit 3d4f0ebb7b
2 changed files with 20 additions and 0 deletions

View File

@@ -65,6 +65,7 @@ module Spree
before_validation :set_cost_currency
before_validation :update_weight_from_unit_value, if: ->(v) { v.product.present? }
before_validation :ensure_unit_value
after_save :save_default_price
after_save :update_units
@@ -297,5 +298,11 @@ module Spree
exchange_variants(:reload).destroy_all
yield
end
def ensure_unit_value
return unless product&.variant_unit == "items" && unit_value.nil?
self.unit_value = 1.0
end
end
end

View File

@@ -783,4 +783,17 @@ module Spree
expect(e.reload.variant_ids).to be_empty
end
end
describe "#ensure_unit_value" do
let(:product) { create(:product, variant_unit: "weight") }
let(:variant) { create(:variant, product_id: product.id) }
context "when a product's variant_unit value is changed from weight to items" do
it "sets the variant's unit_value to 1" do
product.update(variant_unit: "items")
expect(variant.unit_value).to eq 1
end
end
end
end