Ensure that the default Rake task uses the test
environment by default
#810
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
We use the default Rake task as our standard invocation for running the
test suite and other code quality checks. We noticed that running
bundle exec rake
was causing dotenv to use the ENVIRONMENT_NAMEvariable from the .env.development file, and not .env.test as expected.
A recent change in 1d57789 to the values of ENVIRONMENT_NAME in
.env.development hence caused the tests to start failing when run
locally.
We found out that other people have also been experiencing this issue
[1]. The linked comment explains in detail what causes this to happen:
The gist is that dotenv ends up loading the .env.development file
first, and then loads the .env.test file. However, by default dotenv
will not overwrite the variables defined in the first file with those
defined in the second, so we end up with the incorrect ENVIRONMENT_NAME
being used.
The same comment suggested adding
Dotenv.overload('.env.test')
tospec/rails_helper.rb
. This wasn't sufficient for us, since by the timethis happens, our config/initializers/dfe_sign_in.rb had already grabbed
the (wrong) values from the environment.
Anyway, ideally, we don't want to load the .env.development file at
all when running the tests, so I didn't try to figure out how to make
the previous approach work. Instead, we noticed that dotenv contains a
special hack, which sets RAILS_ENV to
test
when the currently-runningRake task is
spec
[2]. There is currently an open pull request ondotenv which does the same thing when running the default Rake task [3],
but it doesn't seem to have attracted any attention.
In the end I decided to emulate the dotenv hack, by setting RAILS_ENV to
test
if running the default Rake task. I do this in the Rakefile,before any of the Rails application is loaded, to ensure that setting
this environment variable happens before dotenv has a chance to load
.development.env.
[1] bkeepers/dotenv#219 (comment)
[2] bkeepers/dotenv#241
[3] bkeepers/dotenv#405