Search code examples
ruby-on-railsenvironment-variablesminitestroda

How best can I define ENV Variables in a Rack based app?


I am playing with RODA by Jeremy Evans https://roda.jeremyevans.net/. However, I am having issues setting Environment Variable for my Test_Environment.

config/initializers/contenful_model.rb

ContentfulModel.configure do |config|
  config.space = ENV.fetch('CONTENTFUL_SPACE_ID')
  config.access_token = ENV.fetch('CONTENTFUL_ACCESS_TOKEN')
  config.environment = "master"
end

.env.rb

case ENV['RACK_ENV'] ||= 'development'
when 'test'
  ENV['CONTENTFUL_SPACE_ID'] ='key-here'
  ENV['CONTENTFUL_ACCESS_TOKEN'] =''
when 'production'
  ENV['CONTENTFUL_SPACE_ID'] ='key-here'
  ENV['CONTENTFUL_ACCESS_TOKEN'] ='key-here'
else
  ENV['CONTENTFUL_SPACE_ID'] ='key-here'
  ENV['CONTENTFUL_ACCESS_TOKEN'] ='key-here'
end

spec/spec_helper.rb

ENV["RACK_ENV"] = "test"
require_relative '../../models/recipe'
require_relative '../../config/initializers/contentful_model'

require_relative '../minitest_helper'

It worked well for development, however, the config in the initializers is not available in the Test environment. I am currently hardcoding those credentials inside spec/spec_helper.rb which doesn't make sense to expose them. I did set ENV variables for Test RACK_ENV in my .env.rb file but it is not reachable from my test environment. How can I get the env variables available to test env??


Solution

  • Apparently, the only problem is that I am not loading the .env.rb file inside the spec helper directory. So solving it for me was to require .env.rb file in my spec_helper.rb and it worked.

    spec/spec_helper.rb

    require_relative '../../.env.rb'