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 

テスト変数はロードされていません - dev環境からロードされています。私のテストファイルは以下の通りです

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

あなたはそれはあなたがこのために別々のファイルを持つことができ、環境に固有の変数が必要な場合は

# .env COINBASE_KEY: devkey COINBASE_SECRET: devsecret 

:ちょうどあなたのGemfilegem 'dotenv-rails'を追加し、.envファイルに共通の変数を置きますこんにちは、私はあなたが 'RAILS_ENV = "test" rails test ... "を探していると信じています。 –

+0

私は自動的に環境変数をロードするものを探しています。テストを実行するたびにRAILS_ENV = "test"と入力する必要はありません。それは非常にun-Railsのようです。 – Dave

+0

〜/ .profileファイル(またはシステムで使用するもの)にエイリアスを追加してみてください。 エイリアスrails = "RAILS_ENV = 'テスト'レール" を実行し、ソース〜/ .profileを実行して現在のターミナルセッションでアクティブにします。 –

答えて

4

カスタムコードを書くことはお勧めしません。環境変数を設定するための既存のソリューションがあります。例えば、dotenv-railsを参照してください。これにより、共通変数を.envファイルに入れることができます。 .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.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

関連する問題