gdelfino
gdelfino

Reputation: 11181

How to show SQL query log generated by a RSpec test?

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)

Upvotes: 52

Views: 31599

Answers (3)

Denis Roarty
Denis Roarty

Reputation: 1

What worked for me is a combination of:

  • Phil's comment above: "in your test.rb file you may also need to set config.log_level = :debug"
  • and viewing the test's log in another terminal with tail -f log/test.log

Upvotes: 0

Chris Ledet
Chris Ledet

Reputation: 11628

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.

Upvotes: 118

Cody Elhard
Cody Elhard

Reputation: 675

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

Upvotes: -2

Related Questions