1

나는 레일 내가이 파일이 (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 

당신이에 대해 별도의 파일을 가질 수 있습니다 안녕하세요, 당신은 'RAILS_ENV = "test"rails test ... "를 찾고 있다고 생각합니다. –

+0

자동으로 환경 변수를로드하는 무언가를 찾고 있습니다. 테스트를 실행할 때마다 RAILS_ENV = "test"를 입력 할 필요가 없습니다. 그것은 매우 un-Rails처럼 보입니다. – Dave

+0

~/.profile 파일 (또는 시스템에서 사용하는 것)에 별명을 추가하십시오. 별칭 레일스 = "RAILS_ENV = '레일'테스트 다음 소스 ~/.profile을 실행하여 현재 터미널 세션에서 활성화하십시오. –

답변

4

이 경우 사용자 지정 코드를 작성하지 않는 것이 좋습니다. 환경 변수 설정을위한 기존 솔루션이 있습니다. 예를 들어 dotenv-rails을 참조하십시오. 그것은 당신이 .env 파일에 공통 변수를 넣을 수 있습니다. 그냥 .env 파일에 공통 변수를 당신의 Gemfilegem 'dotenv-rails'을 추가하고 넣어 : .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'이 될 수도 있지만 구성에서 기본 (개발) 환경의 키를 사용합니다.

는 I는 intializer에서이 부분에서

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 (초기화는 반드시 환경을 존중해야하기 때문에) : before_configuration 블록이 실행하는 최초의 블록 구성 부분임을 보인다 documentation에서를, 그래서 Rails.env 아마 아직 그 시점에서 설정되어 있지 않습니다.

+0

나는 너를 이해하지 못한다. 위 코드 블록을 넣을 파일 이름은 무엇입니까? – Dave

+0

'/ config/initializers'에'environment_variables.rb'라는 파일을 만들고'config.before_configuration'에 현재 가지고있는 코드 블록을 붙여 넣으십시오. 그런 다음 테스트를 실행하십시오. 내가 말했듯이, 그 코드 블록은 어떤 environement가 설정되기 전에 실행될 것입니다. 그러나 초기화 프로그램은 확실히 실행됩니다. – Kkulikovskis

관련 문제