45

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)

gdelfino
  • 11,053
  • 6
  • 44
  • 48
  • 2
    Possible duplicate of [How do I turn on SQL debug logging for ActiveRecord in RSpec tests?](https://stackoverflow.com/questions/5244486/how-do-i-turn-on-sql-debug-logging-for-activerecord-in-rspec-tests) – Jon Schneider Apr 09 '19 at 13:54

2 Answers2

106

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.

Chris Ledet
  • 11,458
  • 7
  • 39
  • 47
  • 5
    in your test.rb file you may also need to set `config.log_level = :debug` – Phil Mar 05 '18 at 19:07
  • 2
    In rails 5.2+, you can also add `ActiveRecord::Base.verbose_query_logs = true` to see the line of code that is triggering each query – Mike Monteiro Jul 21 '21 at 13:10
  • 1
    For Rails >= 7.0, the [`ActiveRecord::Base` method has been deprecated](https://github.com/rails/rails/commit/c3f43075a3c70c3b11717741426ec38a8d3cd14a). You can instead add `ActiveRecord.verbose_query_logs = true` to see lines triggering each query. – Dave Powers Mar 09 '22 at 17:20
  • 5
    `verbose_query_logs = true` is not for showing the query log, it is for showing extra information. You still have to add `ActiveRecord::Base.logger = Logger.new(STDOUT)` to show the log. – khiav reoy Nov 22 '22 at 05:12
-2

According to the Rails 5 docs (Active Record Explain). You can now use the explain method. This will only log the queries you specify, but you will not be overwhelmed if you have a large amount of SQL code before your tests.

ap Model.explain
Cody Elhard
  • 655
  • 1
  • 7
  • 17
  • `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. – Ed Ruder Apr 15 '21 at 05:06