rails: Rake DB tasks don't properly initialize environment when switching from development to test env
When executing Rake DB tasks in development environment they are also executed in test environment (see). This environment change doesn’t prompt the usual intialization but the existing environment config is used, not taking into account that it can dynamically change between environments.
Why is this a problem?
1, Consider the following Rails feature:
The config/database.yml file can contain ERB tags <%= %>. Anything in the tags will be evaluated as Ruby code. You can use this to pull out data from an environment variable or to perform calculations to generate the needed connection information.
For example having different values in test env will not be taken into account in this case. This is known to cause issues with dotenv: https://github.com/bkeepers/dotenv/issues/302.
2, AFAICT Rails.env
and DatabaseTasks.env
are not set correctly after the env change. Amongst other possible issues I believe is the root cause of #26731 which is being solved by hardcoding test env instead of using current_environment
.
3, I would imagine there are further implications which I didn’t discover.
Steps to reproduce
I reproduce the dotenv issue with a dummy project in the gem dotenv_rails_db_tasks_fix (see db config, .env.test, .env.development, test)
Expected behavior
When switching environments the new one is properly initialized at least in a way to respect existing Rails features (i.e. set env variables such as Rails.env
and reload database.yml)
.
Actual behavior
The existing environment config is used, not taking into account that it can dynamically change between environments.
System configuration
Rails version: Rails 5.1.6
Ruby version: ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin17]
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Reactions: 3
- Comments: 16 (5 by maintainers)
Still present. In my experience, this issue affects a lot of people. Would be great to get some sort of feedback.
It’s also an issue for me, where my
config/database.yml
looks like:and trying to run
bin/rails db:structure:load
it runs it twice on same db (just happening to be the same db for development and test), raising errors (as structure cannot be loaded twice on the same db).At least having some switch to turn it off would be helpful.
@deivid-rodriguez Thanks. Yep I saw that issue and my concerns are different here. Although a solution could be made along those lines as well, e.g. a simple ENV option to disable “double” execution would also work. And it is definitely a relevant discussion for those running into this issue.