Rails Console Default Environment

Rails console default environment

The rails executable can't know which environment should run on which machine.

you can put export RAILS_ENV=production in your ~/.bashrc or ~/.bash_profile file of the user you want to start the console with.

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

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.

Rails console not loading environment

This happens when spring is running in production. Try either:

spring stop

or look for running spring process using ps -eaf | grep spring and kill them.

Try the console again once spring is stopped successfully.

How to manually set ENV variables when running rails console

From your console.

env RAILS_MASTER_KEY="..." rails c

See more here https://www.honeybadger.io/blog/ruby-guide-environment-variables/

How can I make a custom environment in rails a default environment?

Ideally you have to set environment variable in .bashrc like

  export RAILS_ENV=staging

because rails is fully dependent on environment variable. But like you said

adding RAILS_ENV in ~/.bashrc or ~/.bash_profile file of the user. will make this application depent on the console, shouldn't it just work independent of ~/.bashrc or ~/.bash_profile file?

Obviously, this is another option. Include this line at the top of config/boot.rb

ENV["RACK_ENV"] = ENV['RAILS_ENV'] || ENV['RACK_ENV'] || "staging"

This will work everywhere. I have tested in following places

  1. Rails 4
  2. Rake
  3. Server
  4. Console
  5. dbconsole
  6. It will pick the environment if it is set in bashrc or zshrc etc.

Rails console won't load environment variables in secrets.yml

TL;DR: spring stop

It turns out, as has happened so many times when things aren't making any sense, Spring is the culprit! I solved this problem (thanks to a related discussion) by running spring stop and then trying again, after which it worked perfectly!

Apparently Spring was caching the environment, or certain pieces of the Rails application, and neglecting to reload them when the environment variables changed.

How to check rails environment?

One liner if you are in app root

rails r "puts Rails.env"



Related Topics



Leave a reply



Submit