46

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?

3 Answers 3

45

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'.

1
  • This answer is specially better because it offers approaches that won't rely on any specific gem specially when using minimalistic frameworks like Sinatra. Thanks!
    – fagiani
    Commented Apr 17, 2017 at 20:57
34

You can use the dotenv gem --- it'll work the same as foreman and load from a .env file. (and a .env.test file for your test environments)

https://github.com/bkeepers/dotenv

1
  • 11
    or, as an alternative, you can RAILS_ENV=test foreman run bundle exec rspec spec Commented May 31, 2013 at 1:51
4

One option is to alias the rspec command to be a little more specific. Put the following line in your dotfiles (.bashrc or .profile or something).

alias 'rspec'='RACK_ENV=test RAILS_ENV=test bundle exec rspec'

Another option is to put environment variables in specific .env files:

# .env.test

RAILS_ENV=test
MONGODB_URI=mongodb://localhost/test
# .. etc ..

Using the dotenv gem works or you can bring them in manually

$ export $(cat .env.test) && rspec

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.