Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4, New App: Why do tests run in development environment?

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?

like image 353
Fitter Man Avatar asked Mar 02 '14 23:03

Fitter Man


1 Answers

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.

like image 107
Fitter Man Avatar answered Sep 29 '22 20:09

Fitter Man