简体   繁体   English

.env 没有被加载到 Rails 的测试环境中,使用 rspec

[英].env not being loaded in test environment in Rails with rspec

I am using gem 'dotenv-rails', '~> 0.9.0' to load environment variables into a Rails 4.0.5 app.我正在使用gem 'dotenv-rails', '~> 0.9.0'将环境变量加载到 Rails 4.0.5 应用程序中。 I have a .env file along with a .env.test.我有一个 .env 文件和一个 .env.test。 All is working well in development, however when it comes to testing, which I do with rspec, it is failing to set the environment variables.一切都在开发中运行良好,但是在我使用 rspec 进行的测试方面,它无法设置环境变量。

I have gone into Rails console in testing environment and I can see they are set to nil.我已经在测试环境中进入 Rails 控制台,我可以看到它们被设置为 nil。

Any tips on how to get dotenv to load in testing?关于如何让 dotenv 在测试中加载的任何提示?

This is a late answer, but for anyone who may find it helpful, add this to spec_helper.rb这是一个迟到的答案,但对于任何可能会发现它有帮助的人,请将其添加到spec_helper.rb

require 'dotenv'
Dotenv.load('.env')

Also, Dotenv.load can accept a list, for example:此外,Dotenv.load 可以接受一个列表,例如:

Dotenv.load(
  '.env.local',
  '.env.test',
  '.env'
)

将此行放在 rspec 设置中的Dotenv::Railtie.load或要加载 dot env 文件的任何页面中。

Dotenv.load(File.expand_path("../../.env.#{Rails.env}", __FILE__))

在研究 Paritosh 的回答后,我发现需要为每个环境指定文件。

If you have test specific environemnt config, You can use Dotenv.overload to overwrite other env config.如果您有测试特定的环境配置,您可以使用Dotenv.overload覆盖其他环境配置。 Just add the following to your spec_helper.rb or rails_helper.rb .只需将以下内容添加到您的spec_helper.rbrails_helper.rb

require "dotenv"
Dotenv.overload ".env.test" 
Dotenv.overload ".env.test.local"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM