RailsApps/rails3-devise-rspec-cucumber — pull request #44 by MarkDBlackwell (2013-03-27 02:28:43+00:00)
Title: Prevent occasional wrong database loss from tests when RAILS_ENV is preset (preventive measure)

Please see Rails issue [7175](https://github.com/rails/rails/issues/7175) for some discussion of this problem.

ENV["RAILS_ENV"] = 'test'

Why do I suggest changing this to '='?:

Because in some cases and with some software, the environment variable RAILS_ENV may be predefined with some value. Then, if it is '||=', running the tests will fail to change that value to 'test', because it already exists. This actually forces the initial database-dropping step to destroy the database of whatever environment RAILS_ENV was predefined to. This may be 'development' or 'production'. Testing normally makes a fresh, empty 'test' environment database during testing.

Why does Rspec have it as '||='?:

This could be motivated by continuous integration servers running tests in a special Rails environment. My source for the possibility is this [comment](https://github.com/rails/rails/issues/7175#issuecomment-11594610). However, to implement continuous integration, pre-setting RAILS_ENV (externally) is unnecessary. Or if desired, the line above can be changed specifically to check for the value 'CI' (or some such), and not just allow any values to pass through, such as 'development'.

Dave Chemlinsky said [here](https://github.com/rspec/rspec-rails/issues/70#issuecomment-268675) he didn't want "to force it to 'test' because that ties everybody's hands." However, if we just want to ensure that RailsApps users are in the 'test' environment whenever they run tests, no one else will be hurt by that.

When running specs (which require spec/spec_helper.rb), one never would want to use any Rails environment other than 'test', right? So, we might as well set it definitely to 'test'.

Without this, under certain circumstances, RailsApps users might suffer the slight frustration of losing their development database, or perhaps worse. I have experienced this loss, BTW.

For instance, the [Foreman](https://devcenter.heroku.com/articles/procfile#developing-locally-with-foreman) gem from Heroku's toolbelt includes general functionality to set environment variables, potentially including RAILS_ENV, by following user-defined directives from a file (.env). It includes a general run command (see Foreman's [man](http://ddollar.github.com/foreman/) page) which might possibly be used to run an app's test suite: `foreman run rake`. And, other software exists for managing Rails development. All have the possibility of this frustrating development database loss during testing, when we easily can afford this protection.