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


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


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