Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.env not being loaded in test environment in Rails with rspec

I am using gem 'dotenv-rails', '~> 0.9.0' to load environment variables into a Rails 4.0.5 app. I have a .env file along with a .env.test. All is working well in development, however when it comes to testing, which I do with rspec, it is failing to set the environment variables.

I have gone into Rails console in testing environment and I can see they are set to nil.

Any tips on how to get dotenv to load in testing?

like image 708
DMH Avatar asked Apr 23 '15 12:04

DMH


3 Answers

If you have test specific environemnt config, You can use Dotenv.overload to overwrite other env config. Just add the following to your spec_helper.rb or rails_helper.rb.

require "dotenv"
Dotenv.overload ".env.test" 
Dotenv.overload ".env.test.local"
like image 185
Derek Avatar answered Oct 20 '22 09:10

Derek


This is a late answer, but for anyone who may find it helpful, add this to spec_helper.rb

require 'dotenv'
Dotenv.load('.env')

Also, Dotenv.load can accept a list, for example:

Dotenv.load(
  '.env.local',
  '.env.test',
  '.env'
)
like image 30
Mike T Avatar answered Oct 20 '22 07:10

Mike T


Dotenv.load(File.expand_path("../../.env.#{Rails.env}", __FILE__))

upon researching Paritosh's answer I found that the file needed to specified per environment.

like image 2
DMH Avatar answered Oct 20 '22 09:10

DMH