ChatGPT解决这个技术问题 Extra ChatGPT

How do I turn on SQL debug logging for ActiveRecord in RSpec tests?

I have some RSpec tests for my models and I would like to turn on SQL ActiveRecord logging just like I see in the Rails server mode. How to do that?

I start my tests with

RAILS_ENV=test bundle exec rspec my/test_spec.rb

Thanks


G
George

You could try setting the ActiveRecord logger to stdout in your test somewhere. If you're using rspec, maybe in the spec helper?

ActiveRecord::Base.logger = Logger.new(STDOUT)

Much more helpful if you're testing a gem with only active_record included as these don't log the SQL by default.
If you are using IRuby (Jupyter for Ruby), STDOUT has been remapped, and you should use $stdout instead.
p
philippe_b

By default, all your db queries will be logged already in test mode. They'll be in log/test.log.


Ah I meant to see it on the console. But this is fair enough.
You can watch it in a console using tail -f log/test.log
I havent realized that this is so easy, so ended up adding a one-lines to dump all instrumentaion from ActiveSupport: ActiveSupport::Notifications.subscribe do |*args| puts *args end
N
Nicolai

set

config.log_level = :info 

in test environment


or set it to config.log_level = :debug to get maximum output, including each SQL statement executed
What config thing is this? As one might expect, I get "undefined local variable or method 'config' for main:Object". Edit: ah this is a Rails thing and not an ActiveRecord thing, nvm...
S
Siwei

if others answers don't work in your case, please check the 'log level' of your test environment.

its default is 'debug', which will output the SQL generated by Rails. if it was set to "info", the SQL will be missing.


P
Pere Joan Martorell

In your test.rb:

Rails.application.configure do
  ...
  config.logger = ActiveSupport::Logger.new(STDOUT)
end