Search code examples
ruby-on-railstestingforemanruby-dotenv

How to set different environment variables for test and development when using Foreman


Currently I store sensitive information (e.g. API keys) in a .env file that is loaded by the Foreman gem. This works well and I am able to access environment variables that are the same in both development and test.

I'd like to be able to use a different set of API keys for my test environment than my development environment.

I tried doing something like .env.development and .env.test based on what I'd seen https://www.rubydoc.info/gems/dotenv/2.7.5

In case it's useful here is the general stack that I'm working with: Rails 5.2.3, Minitest, Guard (to run my tests on save), and Foreman. Currently this app is being deployed to Heroku.

Here's my test_helper.rb:

ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require 'rails/test_help'
require 'vcr'

VCR.configure do |config|
  config.cassette_library_dir = "test/cassettes"
  config.hook_into :faraday
end

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
end

My current work around is to have an additional environment variable with a suffix of _test that I use to override the ENV with in the test_helper.rb. That doesn't feel right to me though.


Solution

  • The .env file will be used by default, but you can make a second file like .env2 and use it with foreman start --env .env2.

    If you are using the dotenv-rails gem to load environment variables, .env.test.local will be automatically loaded for just the test environment.