4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecordで発行されたクエリの数を計測してテストに利用する

Last updated at Posted at 2016-06-27

#特定の処理中に発行されたクエリ数を取得する

気を抜くとN+1問題がすぐ起こりそうな場所があったので
RSpec上で特定の処理中にActiveRecordが発行したクエリの数を取得してみました。

thread = Thread.current
count_up = lambda do |*_args|
  return unless thread == Thread.current
  query_count += 1
end
ActiveSupport::Notifications.subscribed(count_up, 'sql.active_record') do
  User.count
end
p query_count # => 1

ActiveSupport::Notificationsの仕組みを使えばSQLの実行数の他にもテンプレートのレンダリング数とかいろいろ便利に利用できると思います。
Thread.currentのチェックを入れているのはRSpec中にJobをThreadに流しているからです。

#参考になりそうなところ

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?