Same as title: How to get Rails.logger
printing to the console/stdout when running rspec? Eg.
Rails.logger.info "I WANT this to go to console/stdout when rspec is running"
puts "Like how the puts function works"
I still want Rails.logger
to go to log/test.log
too.
This question is related to
ruby-on-rails
logging
rspec
console
stdout
For Rails 4.x the log level is configured a bit different than in Rails 3.x
Add this to config/environment/test.rb
# Enable stdout logger
config.logger = Logger.new(STDOUT)
# Set log level
config.log_level = :ERROR
The logger level is set on the logger instance from config.log_level
at: https://github.com/rails/rails/blob/v4.2.4/railties/lib/rails/application/bootstrap.rb#L70
Environment variable
As a bonus, you can allow overwriting the log level using an environment variable with a default value like so:
# default :ERROR
config.log_level = ENV.fetch("LOG_LEVEL", "ERROR")
And then running tests from shell:
# Log level :INFO (the value is uppercased in bootstrap.rb)
$ LOG_LEVEL=info rake test
# Log level :ERROR
$ rake test
A solution that I like, because it keeps rspec output separate from actual rails log output, is to do the following:
$ tail -f $RAILS_APP_DIR/logs/test.log
or tail -f $RAILS_APP_DIR\logs\test.log
for Window usersIf you are running a multi-pane terminal like iTerm, this becomes even more fun and you have rspec
and the test.log
output side by side.
Tail the log as a background job (&) and it will interleave with rspec output.
tail -f log/test.log &
bundle exec rspec
You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:
def log_test(message)
Rails.logger.info(message)
puts message
end
Source: Stackoverflow.com