Unexpected behavior with `.env` files
erikphansen opened this issue · 5 comments
Thanks for this gem. I discovered it via Prag Prog's Modern Frontend Development for Rails.
I have a Rails app that uses the dotenv-rails
gem for configuration. I do not have a config/database.yml
. Instead I set a DATABASE_URL
in .env.development
and .env.test
files.
My before_server_start
hook includes a call to Rake::Task["db:reset"].invoke
.
When I run bin/rails cypress:run
or bin/rails cypress:open
, the db:reset
call attempts to reset the development database rather than the test database like I'd expect.
After some digging I discovered that when running cypress:run
or cypress:open
the values set in both .env.development
and .env.test
files get used (and the development env vars take precedence over the test env vars). By contrast, running Rails unit tests only activates the values in .env.test
and totally ignores .env.development
. That's the behavior I'd also expect from cypress-rails
.
I'm able to get around this issue by explicitly setting RAILS_ENV=test
before running cypress:run
or cypress:open
. But it feels like that should not be required. Thoughts? Is this a bug or just expected behavior? Or maybe an issue with dotenv-rails
?
Thanks!
Ahh, this sounds like something in the chain (rake, cli, spawning servers) is defaulting to RAILS_ENV=development and then a dotenv-rails load is occurring which blends the two environments to have this effect
I haven't touched this gem in a long time but it sort of feels to me like the CLI should set RAILS_ENV=test
explicitly in such a way that any child processes get it.
Would welcome an investigation and a patch
You articulated that better than I would, but I was thinking along the same lines. I’ll take another look to see if I can come up with a fix that doesn’t break anything.
re: your point about not having touched this gem in a while… Are you still using this gem in projects or have you switched to something else?
I have been testing less with Cypress recently generally, as I've moved most of my new development to Rails 7 + Turbo/Stimulus, I'm finding that system testing with Capybara is plenty for the (small) amount of custom JS I have on each page
As far as I can tell, since cypress:run
is a Rake task, the act of running it (with either bin/rails cypress:run
or bin/rake cypress:run
) is enough to make dotenv-rails
load env vars for the development
env. I don't think this gem can do anything to get around the issue I'm running into. By the time the gem's code runs, rake has already started, and dotenv-rails
has done its thing.
So I'm sticking with simply running RAILS_ENV=test bin/rails cypress:run
Ah yeah. Unfortunate, but something I've been dealing with in gems like this since jasmine-rails in 2011, which exhibited similar issues