From 7274cd779773d1b425c9efc302a411e30c60cf0a Mon Sep 17 00:00:00 2001 From: Martin Meyerhoff Date: Fri, 20 May 2016 07:05:52 -0400 Subject: [PATCH] Validate currency on Spree::Price Currently, the currency of a Spree::Price instance can be set to anything, and the price object won't be invalid. This commit changes this so that only the currencies the Ruby Money library knows are accepted. --- core/app/models/spree/price.rb | 2 ++ core/config/locales/en.yml | 4 ++++ core/spec/models/spree/price_spec.rb | 24 ++++++++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/core/app/models/spree/price.rb b/core/app/models/spree/price.rb index 6947ffe69da..e5c5fc67334 100644 --- a/core/app/models/spree/price.rb +++ b/core/app/models/spree/price.rb @@ -12,6 +12,8 @@ class Price < Spree::Base less_than_or_equal_to: MAXIMUM_AMOUNT } + validates :currency, inclusion: { in: ::Money::Currency.all.map(&:iso_code), message: :invalid_code } + scope :currently_valid, -> { where(is_default: true) } scope :with_default_attributes, -> { where(Spree::Config.default_pricing_options.desired_attributes) } after_save :set_default_price diff --git a/core/config/locales/en.yml b/core/config/locales/en.yml index 57549b46b22..706ddf727d3 100644 --- a/core/config/locales/en.yml +++ b/core/config/locales/en.yml @@ -523,6 +523,10 @@ en: attributes: currency: must_match_order_currency: "Must match order currency" + spree/price: + attributes: + currency: + invalid_code: "is not a valid currency code" spree/promotion: attributes: apply_automatically: diff --git a/core/spec/models/spree/price_spec.rb b/core/spec/models/spree/price_spec.rb index e285ec68e47..6f51a6f3465 100644 --- a/core/spec/models/spree/price_spec.rb +++ b/core/spec/models/spree/price_spec.rb @@ -39,4 +39,28 @@ it { is_expected.to be_valid } end end + + describe "#currency" do + let(:variant) { stub_model Spree::Variant } + subject { Spree::Price.new variant: variant, amount: 10, currency: currency } + + describe "validation" do + context "with an invalid currency" do + let(:currency) { "XYZ" } + + it { is_expected.to be_invalid } + + it "has an understandable error message" do + subject.valid? + expect(subject.errors.messages[:currency].first).to eq("is not a valid currency code") + end + end + + context "with a valid currency" do + let(:currency) { "USD" } + + it { is_expected.to be_valid } + end + end + end end