当我 运行 测试时,如何让 Rails 加载我的测试环境变量?
How do I get Rails to load my test envionrment variables when I run tests?
我正在使用 Rails 5. 我有这个文件,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
我用文件加载它,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
但是当我 运行 我的测试使用
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'])
如何让测试变量在我 运行 测试时默认加载?
编辑: 这是 config/environments/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
根据您原来 post 中的评论,我建议检查 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?
在初始化器中输出,然后检查环境变量。可能会解决问题。 (因为初始化程序肯定应该尊重环境)
更新:从 documentation 看来 before_configuration
块是 运行 的第一个块配置部分,因此 Rails.env
可能尚未设置点.
我不建议为此编写自定义代码。存在用于设置环境变量的现有解决方案。例如,参见 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
我正在使用 Rails 5. 我有这个文件,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
我用文件加载它,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
但是当我 运行 我的测试使用
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'])
如何让测试变量在我 运行 测试时默认加载?
编辑: 这是 config/environments/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
根据您原来 post 中的评论,我建议检查 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?
在初始化器中输出,然后检查环境变量。可能会解决问题。 (因为初始化程序肯定应该尊重环境)
更新:从 documentation 看来 before_configuration
块是 运行 的第一个块配置部分,因此 Rails.env
可能尚未设置点.
我不建议为此编写自定义代码。存在用于设置环境变量的现有解决方案。例如,参见 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