I'm using foreman to start up my rails development server. It's nice that I can put all of my environment variables in the .env
file. Is there a way to do something similar for my test environment?
I want to set an API key that I will use with the vcr
gem, but I don't want to add the API to version control. Any suggestions besides setting the environment variable manually when I start up my tests script?
If you just need to set environment variables, you can either set them from command-line:
SOMETHING=123 SOMETHING_ELSE="this is a test" rake spec
Or you could define the following at the top of your Rakefile or spec_helper.rb:
ENV['SOMETHING']=123
ENV['SOMETHING_ELSE']="this is a test"
If they don't always apply, you could use a conditional:
if something_needs_to_happen?
ENV['SOMETHING']=123
ENV['SOMETHING_ELSE']="this is a test"
end
If you want to use a Foreman .env
file, which looks like:
SOMETHING=123
SOMETHING_ELSE="this is a test"
and turn it into the following and eval it:
ENV['SOMETHING']='123'
ENV['SOMETHING_ELSE']='this is a test'
You might do:
File.open("/path/to/.env", "r").each_line do |line|
a = line.chomp("\n").split('=',2)
a[1].gsub!(/^"|"$/, '') if ['\'','"'].include?(a[1][0])
eval "ENV['#{a[0]}']='#{a[1] || ''}'"
end
though I don't think that would work for multi-line values.
And as @JesseWolgamott noted, it looks like you could use gem 'dotenv-rails'
.