diff --git a/core/app/models/spree/promotion.rb b/core/app/models/spree/promotion.rb index 5f888016ef8..ca63197b85e 100644 --- a/core/app/models/spree/promotion.rb +++ b/core/app/models/spree/promotion.rb @@ -28,6 +28,8 @@ class Promotion < Spree::Base before_save :normalize_blank_values + before_validation :normalize_code + scope :coupons, -> { where.not(code: nil) } scope :advertised, -> { where(advertise: true) } scope :applied, lambda { @@ -227,6 +229,10 @@ def normalize_blank_values end end + def normalize_code + self.code = code.strip if code.present? + end + def match_all? match_policy == 'all' end diff --git a/core/spec/models/spree/promotion_spec.rb b/core/spec/models/spree/promotion_spec.rb index 2a4d9877112..ac78948fbd8 100644 --- a/core/spec/models/spree/promotion_spec.rb +++ b/core/spec/models/spree/promotion_spec.rb @@ -25,6 +25,38 @@ expect(@valid_promotion).not_to be_valid end + describe 'code should be unique' do + let(:code) { 'code' } + + context 'code is unique' do + before do + @valid_promotion.code = code + end + + it { expect(@valid_promotion).to be_valid } + end + + context 'code is not unique' do + let!(:promotion_with_code) { Spree::Promotion.create! name: 'test1', code: code } + + context 'code is identical' do + before do + @valid_promotion.code = code + end + + it { expect(@valid_promotion).not_to be_valid } + end + + context 'code is identical with whitespace' do + before do + @valid_promotion.code = code + ' ' + end + + it { expect(@valid_promotion).not_to be_valid } + end + end + end + describe 'expires_at_must_be_later_than_starts_at' do before do @valid_promotion.starts_at = Date.today