From 95c6a56e2ecd01f4dbd258bf51720f7805702b05 Mon Sep 17 00:00:00 2001 From: Maikel Linke Date: Fri, 12 Jan 2024 16:49:45 +1100 Subject: [PATCH] Simplify loading of default tax category The logic doesn't change but I simplified it and added more detailed specs. --- app/models/spree/variant.rb | 6 +---- spec/models/spree/variant_spec.rb | 39 +++++++++++++++++++++---------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/app/models/spree/variant.rb b/app/models/spree/variant.rb index adfa2b479d..1d8dda53ff 100644 --- a/app/models/spree/variant.rb +++ b/app/models/spree/variant.rb @@ -167,11 +167,7 @@ module Spree end def tax_category - if self[:tax_category_id].nil? - TaxCategory.find_by(is_default: true) - else - TaxCategory.find(self[:tax_category_id]) - end + super || TaxCategory.find_by(is_default: true) end def price_with_fees(distributor, order_cycle) diff --git a/spec/models/spree/variant_spec.rb b/spec/models/spree/variant_spec.rb index d729f08bd5..82317e9571 100644 --- a/spec/models/spree/variant_spec.rb +++ b/spec/models/spree/variant_spec.rb @@ -23,20 +23,35 @@ describe Spree::Variant do end describe "tax category" do - context "when a tax category is required" do - it "is invalid when a tax category is not provided" do - with_products_require_tax_category(true) do - expect(build_stubbed(:variant, tax_category_id: nil)).not_to be_valid - end - end + # `build_stubbed` avoids creating a tax category in the database. + subject(:variant) { build_stubbed(:variant) } + + it "is valid when empty by default" do + expect(variant.tax_category).to eq nil + expect(variant).to be_valid end - context "when a tax category is not required" do - it "is valid when a tax category is not provided" do - with_products_require_tax_category(false) do - expect(build_stubbed(:variant, tax_category_id: nil)).to be_valid - end - end + it "loads the default tax category" do + default = create(:tax_category, is_default: true) + + expect(variant.tax_category).to eq default + expect { + variant.tax_category = nil + }.to_not change { + variant.tax_category + } + expect(variant).to be_valid + end + + it "doesn't load any tax category" do + non_default = create(:tax_category, is_default: false) + expect(variant.tax_category).to eq nil + end + + context "when a tax category is required" do + before { Spree::Config.products_require_tax_category = true } + + it { is_expected.to validate_presence_of :tax_category } end end end