在 Rails 中设置测试环境变量而不放入源代码 [英] Setting Test environment variables in rails without putting in source code
问题描述
我将 Twilio 用于应用程序,在生产中我使用 heroku 的 CLI 设置了身份验证令牌.我正在使用 sms-spec
(https://github.com/monfresh/sms-spec) 在本地测试我的应用程序的 Twilio 集成.我想在测试环境中将 ENV['TWILIO_AUTH_TOKEN']
设置为我的令牌.
I'm using Twilio for an app and on production I set the auth token using heroku's CLI. I'm using sms-spec
(https://github.com/monfresh/sms-spec) to test my app's Twilio integration locally. I want to set ENV['TWILIO_AUTH_TOKEN']
to my token in the test environment.
每当我进行更改时,我都会使用 guard 来自动运行我的测试,因此我不想每次运行测试时都必须手动设置 ENV 变量.出于安全原因,我也不想将令牌放入我的源代码中.
I use guard to auto-run my tests whenever I make changes so I don't want to have to manually set the ENV variable each time I run tests. I also don't want to put the token in my source code for security reasons.
有什么方法可以为我的本地测试环境设置 ENV 变量,使其永久存在而不是在我的源中?我花了几个小时研究这个,似乎找不到如何做到这一点的好解释.非常感谢任何帮助:)
Is there a way I can set the ENV variable for my local test environment such that it is permanent and not in my source? I've spent a few hours researching this and can't seem to find a good explanation of how to do this. Any help is much appreciated :)
推荐答案
两种方法:
- 使用像
Dotenv
这样的 gem(link).这是我在大多数开发应用程序中使用的方法.只需将 gem 包含在您的 gemfile 中,捆绑安装,然后将任何环境变量设置存储在名为.env
的顶级文件中.重新启动 Rails 服务器,ENV 将自动加载.非常易于使用和方便. 如果您在 ENV 部分很灵活,并且您运行的是 Rails 4.1+,则可以使用
config/secrets/yml
.这在 Rails 4.1 发行说明,第 2.2 节中有很好的记录.所以,在你的情况下,你可以这样设置:
- Use a gem like
Dotenv
(link). This is the approach I use in most of my applications for development. Simply include the gem in your gemfile, bundle install and then store any environment variable settings in a top level file called.env
. Restart your rails server and ENV will be automatically loaded. Very easy to use and convenient. If you are flexible on the ENV part, and you are running Rails 4.1+, you can use
config/secrets/yml
. This is documented very well in the Rails 4.1 release notes, Section 2.2. So, in your case, you would set it up like so:
发展:twilio_auth_token:verysecretstring
development: twilio_auth_token: verysecretstring
然后,在您的初始化程序中,您将使用 Rails.application.secrets.twilio_auth_token
,而不是引用 ENV['TWILIO_AUTH_TOKEN']
.我自己没有尝试过,但它在我的清单上,因为我宁愿使用原生 Rails 功能而不是单独的 gem.
Then, in your initializer, instead of referencing ENV['TWILIO_AUTH_TOKEN']
, you would use Rails.application.secrets.twilio_auth_token
. I haven't tried this myself, but it is on my list as I would rather use native Rails functionality than a separate gem.
当然,任何包含您的机密的文件都需要小心保护.至少,确保您包含在 .gitignore
中,这样您的秘密就不会进入您的代码存储库.
Of course, any files which contain your secrets needs to be safeguarded carefully. At a minimum, make sure you include in .gitignore
so that your secrets do not find their way into your code respository.
这篇关于在 Rails 中设置测试环境变量而不放入源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!