2024-02-10 16:18:56 -06:00
|
|
|
require "test_helper"
|
2024-05-02 10:18:06 -04:00
|
|
|
require "ostruct"
|
2024-02-10 16:18:56 -06:00
|
|
|
class ExchangeRateTest < ActiveSupport::TestCase
|
2024-03-27 09:16:00 -06:00
|
|
|
test "find rate in db" do
|
|
|
|
assert_equal exchange_rates(:day_29_ago_eur_to_usd),
|
|
|
|
ExchangeRate.find_rate_or_fetch(from: "EUR", to: "USD", date: 29.days.ago.to_date)
|
|
|
|
end
|
|
|
|
|
|
|
|
test "fetch rate from provider when it's not found in db" do
|
2024-05-27 18:10:28 +02:00
|
|
|
with_env_overrides SYNTH_API_KEY: "true" do
|
|
|
|
ExchangeRate
|
|
|
|
.expects(:fetch_rate_from_provider)
|
|
|
|
.returns(ExchangeRate.new(base_currency: "USD", converted_currency: "MXN", rate: 1.0, date: Date.current))
|
2024-03-27 09:16:00 -06:00
|
|
|
|
2024-05-27 18:10:28 +02:00
|
|
|
ExchangeRate.find_rate_or_fetch from: "USD", to: "MXN", date: Date.current
|
|
|
|
end
|
2024-03-27 09:16:00 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
test "provided rates are saved to the db" do
|
2024-05-27 18:10:28 +02:00
|
|
|
with_env_overrides SYNTH_API_KEY: "true" do
|
|
|
|
VCR.use_cassette "synth_exchange_rate" do
|
|
|
|
assert_difference "ExchangeRate.count", 1 do
|
|
|
|
ExchangeRate.find_rate_or_fetch from: "USD", to: "MXN", date: Date.current
|
|
|
|
end
|
2024-03-27 09:16:00 -06:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
test "retrying, then raising on provider error" do
|
2024-05-27 18:10:28 +02:00
|
|
|
with_env_overrides SYNTH_API_KEY: "true" do
|
|
|
|
Faraday.expects(:get).returns(OpenStruct.new(success?: false)).times(3)
|
2024-03-27 09:16:00 -06:00
|
|
|
|
2024-05-27 18:10:28 +02:00
|
|
|
error = assert_raises Provider::Base::ProviderError do
|
|
|
|
ExchangeRate.find_rate_or_fetch from: "USD", to: "MXN", date: Date.current
|
|
|
|
end
|
2024-03-27 09:16:00 -06:00
|
|
|
|
2024-05-27 18:10:28 +02:00
|
|
|
assert_match "Failed to fetch exchange rate from Provider::Synth", error.message
|
|
|
|
end
|
2024-03-27 09:16:00 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
test "retrying, then raising on network error" do
|
2024-05-27 18:10:28 +02:00
|
|
|
with_env_overrides SYNTH_API_KEY: "true" do
|
|
|
|
Faraday.expects(:get).raises(Faraday::TimeoutError).times(3)
|
2024-03-27 09:16:00 -06:00
|
|
|
|
2024-05-27 18:10:28 +02:00
|
|
|
assert_raises Faraday::TimeoutError do
|
|
|
|
ExchangeRate.find_rate_or_fetch from: "USD", to: "MXN", date: Date.current
|
|
|
|
end
|
2024-03-27 09:16:00 -06:00
|
|
|
end
|
|
|
|
end
|
2024-02-10 16:18:56 -06:00
|
|
|
end
|