diff --git a/app/models/concerns/calculated_adjustments.rb b/app/models/concerns/calculated_adjustments.rb index aa9143a091..3e0043c61a 100644 --- a/app/models/concerns/calculated_adjustments.rb +++ b/app/models/concerns/calculated_adjustments.rb @@ -5,6 +5,18 @@ require "active_support/concern" module CalculatedAdjustments extend ActiveSupport::Concern + CALCULATORS = %w{ + Calculator::DefaultTax + Calculator::FlatPercentItemTotal + Calculator::FlatPercentPerItem + Calculator::FlatRate + Calculator::FlexiRate + Calculator::None + Calculator::PerItem + Calculator::PriceSack + Calculator::Weight + }.freeze + included do has_one :calculator, as: :calculable, class_name: "Spree::Calculator", dependent: :destroy accepts_nested_attributes_for :calculator @@ -32,7 +44,11 @@ module CalculatedAdjustments end def calculator_type=(calculator_type) - klass = calculator_type.constantize if calculator_type + return unless calculator_type + + return unless CALCULATORS.include?(calculator_type) + + klass = calculator_type.constantize self.calculator = klass.new if klass && !calculator.is_a?(klass) end diff --git a/spec/models/concerns/calculated_adjustments_spec.rb b/spec/models/concerns/calculated_adjustments_spec.rb index 73238a055c..01eda5fbd1 100644 --- a/spec/models/concerns/calculated_adjustments_spec.rb +++ b/spec/models/concerns/calculated_adjustments_spec.rb @@ -67,4 +67,30 @@ RSpec.describe CalculatedAdjustments do end end end + + describe "#calculator_type=" do + subject(:tax_rate) { Spree::TaxRate.new } + + it "set the calculator to the given type" do + tax_rate.calculator_type = "Calculator::FlatRate" + + expect(tax_rate.calculator).to be_a(Calculator::FlatRate) + end + + context "when no argument given" do + it "returns nil" do + tax_rate.calculator_type = nil + + expect(tax_rate.calculator).to be_nil + end + end + + context "when not allowed calculator type given" do + it "returns nil" do + tax_rate.calculator_type = "Calculator::Wrong" + + expect(tax_rate.calculator).to be_nil + end + end + end end