Skip to content

Commit

Permalink
Add convert currency and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Edge7481 committed Apr 1, 2024
1 parent 1a7adf8 commit 8d7d821
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
11 changes: 11 additions & 0 deletions app/models/currency_conversion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,15 @@ class CurrencyConversion < ApplicationRecord
belongs_to :conference
validates :rate, numericality: { greater_than: 0 }
validates :from_currency, uniqueness: { scope: :to_currency }, on: :create

def self.convert_currency(conference, amount, from_currency, to_currency)
conversion = conference.currency_conversions.find_by(from_currency: from_currency, to_currency: to_currency)
if conversion
Money.add_rate(from_currency, to_currency, conversion.rate)
amount.exchange_to(to_currency)
else
# If no conversion is found. Should not be possible with the currency design of fixed allowed currencies.
amount
end
end
end
23 changes: 23 additions & 0 deletions spec/models/currency_conversion_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

describe CurrencyConversion do
let!(:conference) { create(:conference, title: 'ExampleCon') }
let(:amount) { Money.from_amount(10.00, 'USD') }

describe 'validations' do
before do
Expand All @@ -34,4 +35,26 @@

it { is_expected.to validate_uniqueness_of(:from_currency).scoped_to(:to_currency).on(:create) }
end

describe 'convert currency functionality' do
context 'when conversion rate exists' do
before do
conference.currency_conversions << create(:currency_conversion, from_currency: 'USD', to_currency: 'EUR', rate: 0.89)
conference.currency_conversions << create(:currency_conversion, from_currency: 'USD', to_currency: 'GBP', rate: 0.75)
end

it 'converts currency using existing rate' do
converted_amount = described_class.convert_currency(conference, amount, 'USD', 'EUR')
expect(converted_amount.currency).to eq('EUR')
expect(converted_amount.cents).to eq(890)
end
end

context 'when conversion rate does not exist' do
it 'returns the original amount if no conversion is found' do
original_amount = described_class.convert_currency(conference, amount, 'USD', 'INR')
expect(original_amount.cents).to eq(1000)
end
end
end
end

0 comments on commit 8d7d821

Please sign in to comment.