How to show SQL query log generated by a RSpec test?
22,535
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.
Author by
gdelfino
Data processing, automation, visualization, algorithms, web technology, automotive industry and even electoral studies. Significant experience with Mathematica & MATLAB.
Updated on July 09, 2022Comments
-
gdelfino almost 2 years
I am writing a spec for my rails 3 application. I want to test that db transactions are really working. It would be really helpful to be able to see the sql queries being generated my app while being driven by the spec.
Is there a way to see the queries just like in the rails console?
I'm using Rails 3.0.9, RSpec 2.6, and sqlite (will move to mysql later on)
-
Phil about 6 yearsin your test.rb file you may also need to set
config.log_level = :debug
-
Ed Ruder about 3 years
Model.explain
doesn't log queries–it executes the DB's EXPLAIN command, which gives you information about how the query will run. Info like: whether it uses an index, how many rows of the DB the query will need to examine, etc. -
Mike Monteiro almost 3 yearsIn rails 5.2+, you can also add
ActiveRecord::Base.verbose_query_logs = true
to see the line of code that is triggering each query -
Dave Powers about 2 yearsFor Rails >= 7.0, the
ActiveRecord::Base
method has been deprecated. You can instead addActiveRecord.verbose_query_logs = true
to see lines triggering each query.