Skip to content

Commit

Permalink
Set RAILS_ENV to test when executing the default rake task
Browse files Browse the repository at this point in the history
This is a followup of #241 and brings the `dotenv-rails` environment
assigning hack in line with the [logic rails uses when the
`test_unit/railtie` is loaded][1].

This is a breaking change for all non `test-unit` users, but brings the
behavior of `dotenv-rails` in line across all uses of `rake test`, `rake
rspec`, `rspec` and `rake`.

Before this change `dotenv-rails` loaded different env files when using
a rails application with `rspec` for tests. `rake spec` was covered by
the previous logic and set the RAILS_ENV to test. Only running `rake`
(which invokes rspec by default) wasn't covered and thus loaded first
the development env files and later the test env.

[1]: https://github.com/rails/rails/blob/6-0-stable/railties/lib/rails/test_unit/railtie.rb#L5-L7
  • Loading branch information
dsander committed Jan 3, 2020
1 parent 284e4e6 commit c047f03
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/dotenv/rails.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require "dotenv"

# Fix for rspec rake tasks loading in development
# Fix for rake tasks loading in development
#
# Dotenv loads environment variables when the Rails application is initialized.
# When running `rake`, the Rails application is initialized in development.
Expand All @@ -9,8 +9,10 @@
#
# See https://github.com/bkeepers/dotenv/issues/219
if defined?(Rake.application)
if Rake.application.top_level_tasks.grep(/^(parallel:spec|spec(:|$))/).any?
Rails.env = ENV["RAILS_ENV"] ||= "test"
task_regular_expression = /^(default$|parallel:spec|spec(:|$))/
if Rake.application.top_level_tasks.grep(task_regular_expression).any?
environment = Rake.application.options.show_tasks ? "development" : "test"
Rails.env = ENV["RAILS_ENV"] ||= environment
end
end

Expand Down

0 comments on commit c047f03

Please sign in to comment.