From 23a7ba24799d1f956c5f44af9e8995b63156db36 Mon Sep 17 00:00:00 2001 From: "Nihal M. Kelanthodika" Date: Thu, 27 Jan 2022 15:50:20 +0530 Subject: [PATCH 1/2] Added before_save callback to convert variant weight to decimal and 0.0 if nil --- app/models/spree/variant.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/models/spree/variant.rb b/app/models/spree/variant.rb index 1b2b085de1..8f61819708 100644 --- a/app/models/spree/variant.rb +++ b/app/models/spree/variant.rb @@ -79,6 +79,8 @@ module Spree after_create :create_stock_items after_create :set_position + before_save :convert_variant_weight_to_decimal + around_destroy :destruction # default variant scope only lists non-deleted variants @@ -243,5 +245,9 @@ module Spree self.unit_value = 1.0 end + + def convert_variant_weight_to_decimal + self.weight = weight.to_d + end end end From ddaac654efaa59d886313c9c44057e02ee37a189 Mon Sep 17 00:00:00 2001 From: "Nihal M. Kelanthodika" Date: Thu, 27 Jan 2022 16:11:06 +0530 Subject: [PATCH 2/2] Add specs for conversion of variant weight input into decimal/0.0 --- spec/models/spree/variant_spec.rb | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/spec/models/spree/variant_spec.rb b/spec/models/spree/variant_spec.rb index 548f82e1d8..73a1f79660 100644 --- a/spec/models/spree/variant_spec.rb +++ b/spec/models/spree/variant_spec.rb @@ -525,6 +525,38 @@ module Spree expect(product.master).to be_valid end end + + context "when the product's unit is non-weight" do + before do + product.update_attribute :variant_unit, 'volume' + product.reload + variant.reload + end + + it "sets weight to decimal before save if it's integer" do + variant.weight = 1 + variant.save! + expect(variant.weight).to eq 1.0 + end + + it "sets weight to 0.0 before save if it's nil" do + variant.weight = nil + variant.save! + expect(variant.weight).to eq 0.0 + end + + it "sets weight to 0.0 if input is a non numerical string" do + variant.weight = "BANANAS!" + variant.save! + expect(variant.weight).to eq 0.0 + end + + it "sets weight to correct decimal value if input is numerical string" do + variant.weight = "2" + variant.save! + expect(variant.weight).to eq 2.0 + end + end end describe "unit value/description" do