Skip to content

Commit

Permalink
Merge pull request #470 from bkeepers/rake-test-rails-env
Browse files Browse the repository at this point in the history
Rake test rails env
  • Loading branch information
bkeepers committed Jan 21, 2024
2 parents 2202e3e + 832ebbc commit 9107dc2
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions lib/dotenv/rails.rb
Expand Up @@ -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
Expand All @@ -77,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
Expand Down

0 comments on commit 9107dc2

Please sign in to comment.