Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix environment run running rake test #470

Merged
merged 2 commits into from
Jan 21, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 18 additions & 15 deletions lib/dotenv/rails.rb
Original file line number Diff line number Diff line change
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