samedi 23 septembre 2017

How do I get Rails to load my test envionrment variables when I run tests?

I'm using Rails 5. I have this file, config/environment_variables.yml

development:
  COINBASE_KEY: devkey
  COINBASE_SECRET: devsecret
test:
  COINBASE_KEY: testkey
  COINBASE_SECRET: testsecret
production:
  COINBASE_KEY: prodkey
  COINBASE_SECRET: prodsecret

I load it with the file, config/initializers/environment_variables.rb

module EnvironmentVariables
  class Application < Rails::Application
    config.before_configuration do
      env_file = Rails.root.join("config", 'environment_variables.yml').to_s

      if File.exists?(env_file)
        YAML.load_file(env_file)[Rails.env].each do |key, value|
          ENV[key.to_s] = value
        end # end YAML.load_file
      end # end if File.exists?
    end # end config.before_configuration
  end # end class
end # end module

but when I run my test using

rails test test/services/crypto_currency_service_test.rb

The test variables aren't loading -- rather those from the dev environment are loading. Below is my test file

require 'coinbase/wallet'
require 'minitest/mock'

class CryptoCurrencyServiceTest <  ActiveSupport::TestCase

  test 'sell' do
    last_transaction = MyTransaction.new({
      :transaction_type => "buy",
      :amount_in_usd => "100",
      :btc_price_in_usd => "3000"
    })

    puts "env: #{ENV['COINBASE_KEY']}"
    @client = Coinbase::Wallet::Client.new(api_key: ENV['COINBASE_KEY'], api_secret: ENV['COINBASE_SECRET'])

How do I get the test variables to load by default when I run tests?

Aucun commentaire:

Enregistrer un commentaire