How do I get an ENV variable set for rspec?
Solution 1
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
Solution 2
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'
.
Solution 3
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
Related videos on Youtube
Cyrus
Updated on October 20, 2020Comments
-
Cyrus over 3 years
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? -
Jesse Wolgamott almost 11 yearsor, as an alternative, you can
RAILS_ENV=test foreman run bundle exec rspec spec
-
Dave Sag over 10 yearsThat's exactly what I was looking for. Thanks
-
fagiani about 7 yearsThis answer is specially better because it offers approaches that won't rely on any specific
gem
specially when using minimalistic frameworks likeSinatra
. Thanks!