From a9a9335bdd6fec1e64ff27aa2a357bfcc26d60e2 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Sun, 21 Jan 2024 08:11:23 -0500 Subject: [PATCH 1/2] Load test wen running `rake test` --- lib/dotenv/rails.rb | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/lib/dotenv/rails.rb b/lib/dotenv/rails.rb index 4a3ce4c1..74cf2644 100644 --- a/lib/dotenv/rails.rb +++ b/lib/dotenv/rails.rb @@ -48,24 +48,21 @@ def root ::Rails.root || Pathname.new(ENV["RAILS_ROOT"] || Dir.pwd) end + # The current environment that the app is running in. + # + # When running `rake`, the Rails application is initialized in development, so we have to + # check which rake tasks are being run to determine the environment. + # + # See https://github.com/bkeepers/dotenv/issues/219 def env - env = ::Rails.env - - # Dotenv loads environment variables when the Rails application is initialized. - # When running `rake`, the Rails application is initialized in development. - # Rails includes some hacks to set `RAILS_ENV=test` when running `rake test`, - # but rspec does not include the same hacks. - # - # See https://github.com/bkeepers/dotenv/issues/219 - if defined?(Rake.application) - task_regular_expression = /^(default$|parallel:spec|spec(:|$))/ - if Rake.application.top_level_tasks.grep(task_regular_expression).any? - env = ActiveSupport::EnvironmentInquirer.new(Rake.application.options.show_tasks ? "development" : "test") - end + @env ||= if defined?(Rake.application) && Rake.application.top_level_tasks.grep(TEST_RAKE_TASKS).any? + env = Rake.application.options.show_tasks ? "development" : "test" + ActiveSupport::EnvironmentInquirer.new(env) + else + ::Rails.env end - - env end + TEST_RAKE_TASKS = /^(default$|test(:|$)|parallel:spec|spec(:|$))/ def deprecator # :nodoc: @deprecator ||= ActiveSupport::Deprecation.new From 832ebbc10361d3c060c6118a3ee4610b56240404 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Sun, 21 Jan 2024 08:16:44 -0500 Subject: [PATCH 2/2] Log what was loaded when Rails.logger is initialized --- lib/dotenv/rails.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/dotenv/rails.rb b/lib/dotenv/rails.rb index 74cf2644..81a2f17f 100644 --- a/lib/dotenv/rails.rb +++ b/lib/dotenv/rails.rb @@ -74,6 +74,12 @@ def self.load instance.load end + # Rails.logger was not intialized when dotenv loaded. Wait until it is and log what happened. + initializer "dotenv", after: :initialize_logger do |app| + loaded_files = files.select(&:exist?).map { |p| p.relative_path_from(root).to_s } + ::Rails.logger.debug "dotenv loaded ENV from #{loaded_files.to_sentence}" + end + initializer "dotenv.deprecator" do |app| app.deprecators[:dotenv] = deprecator end