如何在 RSpec 测试中为 ActiveRecord 打开 SQL 调试日志记录?

我对我的模型进行了一些 RSpec 测试,我希望像在 Rails 服务器模式中看到的那样打开 SQLActiveRecord 日志记录。怎么做?

我的测试开始于

RAILS_ENV=test bundle exec rspec my/test_spec.rb

谢谢

81629 次浏览

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

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)

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.

set

config.log_level = :info

in test environment

In your test.rb:

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