Strip leading and trailing whitespace from code on assignment instead of before validation

Co-authored-by: Maikel <maikel@email.org.au>
This commit is contained in:
Cillian O'Ruanaidh
2023-08-04 10:15:22 +01:00
parent ab0d899a17
commit 9eba266efc
2 changed files with 6 additions and 11 deletions

View File

@@ -10,12 +10,14 @@ class Voucher < ApplicationRecord
class_name: 'Spree::Adjustment',
dependent: :nullify
before_validation :strip_code
validates :code, length: { maximum: STRING_COLUMN_LIMIT },
presence: true, uniqueness: { scope: :enterprise_id }
validates :amount, presence: true, numericality: { greater_than: 0 }
def code=(value)
super(value.to_s.strip)
end
def display_value
Spree::Money.new(amount)
end
@@ -46,10 +48,4 @@ class Voucher < ApplicationRecord
def compute_amount(order)
-amount.clamp(0, order.pre_discount_total)
end
private
def strip_code
code.strip! if code.present?
end
end

View File

@@ -10,10 +10,9 @@ describe Voucher do
it { is_expected.to have_many(:adjustments) }
end
context "before validation" do
it "removes leading and trailing whitespace from the code" do
describe '#code=' do
it "removes leading and trailing whitespace" do
voucher = build(:voucher, code: "\r\n\t new_code \r\n\t")
voucher.valid?
expect(voucher.code).to eq("new_code")
end