From 9eba266efc92a52e13734b719c46238cff4d24fd Mon Sep 17 00:00:00 2001 From: Cillian O'Ruanaidh Date: Fri, 4 Aug 2023 10:15:22 +0100 Subject: [PATCH] Strip leading and trailing whitespace from code on assignment instead of before validation Co-authored-by: Maikel --- app/models/voucher.rb | 12 ++++-------- spec/models/voucher_spec.rb | 5 ++--- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/app/models/voucher.rb b/app/models/voucher.rb index e963c2ab92..62eb661be1 100644 --- a/app/models/voucher.rb +++ b/app/models/voucher.rb @@ -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 diff --git a/spec/models/voucher_spec.rb b/spec/models/voucher_spec.rb index f965904ab1..5d8c4844e9 100644 --- a/spec/models/voucher_spec.rb +++ b/spec/models/voucher_spec.rb @@ -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