53

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)

1

3 Answers 3

119

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.

Sign up to request clarification or add additional context in comments.

4 Comments

in your test.rb file you may also need to set config.log_level = :debug
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
For Rails >= 7.0, the ActiveRecord::Base method has been deprecated. You can instead add ActiveRecord.verbose_query_logs = true to see lines triggering each query.
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.
0

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

Comments

-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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.