How to run Rails console in the test environment and load test_helper.rb?

The background: I'm having some problems with Thoughtbot's "Factory Girl" gem, with is used to create objects to use in unit and other tests. I'd like to go to the console and run different Factory Girl calls to check out what's happening. For example, I'd like to go in there are do...

>> Factory(:user).inspect

I know that you can run the console in different environments...

$ script/console RAILS_ENV=test

But when I do that, Factory class is not available. It looks as though test_helper.rb is not getting loaded.

I tried various require calls including one with the absolute path to test_helper.rb but they fail similarly to this:

$ script/console RAILS_ENV=test
>> require '/Users/ethan/project/contactdb/test/test_helper.rb'
  Errno::ENOENT: No such file or directory - 
  /Users/ethan/project/contactdb/config/environments/RAILS_ENV=test.rb

Grr. Argh.


Solution 1:

For Rails < 3.0

Run script/console --help. You'll notice that the syntax is script/console [environment], which in your case is script/console test.

I'm not sure if you have to require the test helper or if the test environment does that for you, but with that command you should at least be able to boot successfully into the test env.

As a sidenote: It is indeed kind of odd that the various binaries in script/ has different ways of setting the rails environment.

For Rails 3 and 4

Run rails c test. Prepend bundle exec if you need this for the current app environment.

For Rails 5 and 6

Run rails console -e test.

Solution 2:

In Rails 3, just do rails console test or rails console production or rails console development (which is the default).

Solution 3:

For Rails 5.2.0: "Passing the environment's name as a regular argument is deprecated and will be removed in the next Rails version. Please, use the -e option instead."

rails c -e test