How do I turn on SQL debug logging for ActiveRecord in RSpec tests?
By default, all your db queries will be logged already in test mode. They'll be in log/test.log
.
How to show SQL query log generated by a RSpec test?
Put the following code in your specs:
Rails 7.0+
ActiveRecord.verbose_query_logs = true
Rails 5.2
ActiveRecord::Base.verbose_query_logs = true
Rails 3.0
ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?(ActiveRecord::Base)
Thanks to everyone who commented for the Rails updates.
Rspec log sql to console for filtered / tagged specs
I had to use before
and after
in my spec_helper.rb
# log SQL to console for tests tagged with :db
config.before(:each, db: true) do
@default_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(STDOUT)
end
# log SQL to console for tests tagged with :db
config.after(:each, db: true) do
ActiveRecord::Base.logger = @default_logger
end
I liked the idea of having the "ensure" possibility suggested from Paul N. and get rid of the instance variable. Paul N.'s approach raises syntax errors as the ensure
clause can only be run inside a method.
def with_std_out_logger
default_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = Logger.new(STDOUT)
yield
ensure
ActiveRecord::Base.logger = default_logger
end
config.around(:each, db: true) do |example|
with_std_out_logger { example.run }
end
How do I turn off Rails SQL logging in test?
Ok I found it. This worked:
config.after_initialize do
ActiveRecord::Base.logger = nil
end
Suppress Rails logging for specific ActiveRecord request
Silence
I don't have a specific answer for your question, but we use ActiveRecord::Base.logger.silence
to silence the logger:
ActiveRecord::Base.logger.silence do
# your method here
end
It's not for specific requests, but works for actions you may wish to stop logging. Perhaps you could extend ActiveRecord::Base
to silence a specific method?
--
Extending ActiveRecord
Perhaps you could mix what I've described with extending ActiveRecord? The recommendation on this question is to use an ActiveRecord concern.
I've never used one of these - can put together some code if you feel applicable
Rails3 SQL logging output in a separate file
ActiveRecord::Base.logger = Logger.new('log/development_sql.log')
Related Topics
How to Seed the Production Database Using the Capistrano Gem
How to Make the Say Command Echo a Variable Value in a Script
How to Make the Days of the Month Be Printed According to Each Day (Ex: Su Mo Tu We...Etc)
Iterating Over the Registers of a Yardoc '@Macro'
Fetch VS. [] When Working with Hashes
Difference Between Block and &Block in Ruby
Gracefully Shutting Down Sidekiq Processes
Get File Name and Extension in Ruby
How to List All Databases with Activerecord
Using a Duration Field in a Rails Model
How to Understand Strptime VS. Strftime
Rails Console Is Not Outputting SQL Statements to My Development Log