Setting Test environment variables in rails without putting in source code

你离开我真会死。 提交于 2020-01-25 08:42:07

问题


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.

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.

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 :)


回答1:


Two approaches:

  1. 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.
  2. 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:

    development: twilio_auth_token: verysecretstring

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.

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.



来源:https://stackoverflow.com/questions/31196212/setting-test-environment-variables-in-rails-without-putting-in-source-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!