I have simple, new Rails 4 app which clobbers the development database when I run rake test:units
, even though I've set the RAILS_ENV in test_helper.rb. I wouldn't have expected that. Here are the simple steps to reproduce it.
I have Ruby 2.0.0p247 and Rails 4.0.1.
rails new foo
rails generate scaffold gadget
rake db:migrate
I edit test/models/gadget_test.rb to look like this:
require 'test_helper'
class GadgetTest < ActiveSupport::TestCase
test "the env" do
assert_equal "test", Rails.env
end
end
and I have edited the first line of test/test_helper.rb from
ENV["RAILS_ENV"] ||= "test"
to be
ENV["RAILS_ENV"] = "test"
Even so, when the tests invoke rake test:units
it fails:
1) Failure:
GadgetTest#test_the_env test/models/gadget_test.rb:5]:
Expected: "test"
Actual: "development"
With older (Rails 3) apps I've set up, I could count on this defaulting to the test environment. What am I missing?
Mystery solved, with a big tip of the hat to j_mcnally!
To force the Rails env to "test" in Rails 4 (and probably much earlier), it no longer suffices to change the first line of the test_helper.rb to
ENV["RAILS_ENV"] = "test"
This fails to reset the cached value of Rails.env, but if you invoke
Rails.env = "test"
It will reset the cached value properly. That said, there are other places where Rails.env is being invoked already, otherwise the cache wouldn't be set. One obvious one is bundler setup in application.rb, where it has Bundler.require(:default, Rails.env)
and changing that to Bundler.require(:default, ENV['RAILS_ENV'])
(to avoid setting the cache) still indicates that other places in the initialization must also be invoking Rails.env. The significance of all of that is that some of the setup is going to think it's running in development and then the tests will run in the "test" environment.
Net answer: I have a way to get what I want, but there may still be some danger spots lurking out there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With