1

我使用Rails 5.我有這個文件,配置/ environment_variables.yml當我運行測試時,如何讓Rails加載我的測試環境變量?

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

我與文件加載它,配置/初始化/ 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 

但是當我運行使用

rails test test/services/crypto_currency_service_test.rb 

測試變量不加載我的測試 - 而那些從開發環境加載。以下是我的測試文件

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']) 

當我運行測試時,如何獲取默認加載的測試變量?

編輯:這裏的配置/環境/ test.rb文件,我還沒有(有意識地)改變...

Rails.application.configure do 
    # Settings specified here will take precedence over those in config/application.rb. 

    # The test environment is used exclusively to run your application's 
    # test suite. You never need to work with it otherwise. Remember that 
    # your test database is "scratch space" for the test suite and is wiped 
    # and recreated between test runs. Don't rely on the data there! 
    config.cache_classes = true 

    # Do not eager load code on boot. This avoids loading your whole application 
    # just for the purpose of running a single test. If you are using a tool that 
    # preloads Rails for running tests, you may have to set it to true. 
    config.eager_load = false 

    # Configure public file server for tests with Cache-Control for performance. 
    config.public_file_server.enabled = true 
    config.public_file_server.headers = { 
    'Cache-Control' => 'public, max-age=3600' 
    } 

    # Show full error reports and disable caching. 
    config.consider_all_requests_local  = true 
    config.action_controller.perform_caching = false 

    # Raise exceptions instead of rendering exception templates. 
    config.action_dispatch.show_exceptions = false 

    # Disable request forgery protection in test environment. 
    config.action_controller.allow_forgery_protection = false 
    config.action_mailer.perform_caching = false 

    # Tell Action Mailer not to deliver emails to the real world. 
    # The :test delivery method accumulates sent emails in the 
    # ActionMailer::Base.deliveries array. 
    config.action_mailer.delivery_method = :test 

    # Print deprecation notices to the stderr. 
    config.active_support.deprecation = :stderr 

    # Raises error for missing translations 
    # config.action_view.raise_on_missing_translations = true 
end 
+0

您好,我相信您正在尋找'RAILS_ENV =「test」rails test ...' –

+0

我正在尋找能自動加載環境變量的東西。我不想在每次運行測試時都輸入RAILS_ENV =「test」。這看起來非常不合Rails。 – Dave

+0

嘗試添加〜/ .profile文件的別名(或您的系統使用的)。沿着 別名rails =「RAILS_ENV ='test'rails」 然後運行source〜/ .profile爲當前終端會話激活它。 –

回答

4

我不會爲此編寫自定義代碼。現有的解決方案可用於設置環境變量。例如,請參閱dotenv-rails。它允許你把公共變量放到.env文件中。只需添加gem 'dotenv-rails'Gemfile,把公共變量爲.env文件:

# .env 
COINBASE_KEY: devkey 
COINBASE_SECRET: devsecret 

如果您需要特定的環境變量,它可以讓你有這個單獨的文件:.env.development.env.test.env.production

#.env.test 

COINBASE_KEY: testkey 
COINBASE_SECRET: testsecret 


#.env.production 

COINBASE_KEY: prodkey 
COINBASE_SECRET: prodsecret 
+0

這些「.env」文件位於何處?在我的項目的根源? – Dave

+0

@Dave是的,在你的項目的根源 – Hirurg103

0

從您的原始文章的評論,我建議檢查是否config.before_configuration模塊沒有故障。可能是在該塊運行之後加載rails環境的情況,因此當您在測試中打印該內容時獲得Rails.env == 'test',但在配置中,它會從默認(開發)環境中獲取密鑰。

也許我建議把這個部分

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? 

出一個初始化器,然後檢查的環境變量。可能解決這個問題。 (因爲初始化一定要尊重環境)

UPDATE:從documentation似乎before_configuration塊是第一個塊的配置的一部分來運行,所以Rails.env可能尚未確定在這一點上。

+0

我不理解你。你希望我把上面的代碼塊放在什麼位置? – Dave

+0

只需在'/ config/initializers'中創建一個名爲'environment_variables.rb'的文件,並將當前擁有的代碼塊粘貼到'config.before_configuration'中。然後運行測試。正如我所說,該代碼塊可能在任何環境設置之前運行,但初始化程序肯定會運行。 – Kkulikovskis

相關問題