0
0

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 1 year has passed since last update.

rspecで該当部分のSQLのログをコンソールに出力する

Posted at

背景

実際にどんなSQL出てるのか見たい。
ローカルで単発想定。

belongs_toのvalidationでSQL呼ばれてるとかに気付くことができる。

出力方法

.rb
    # before
    # subject { described_class.start!(user_id: user.id) }

    # after
    subject do
      user_id = user.id
      using_sql_logger do
        described_class.start!(user_id:)
      end
    end

こう書き換えるとSQLが出力されるようにした。

準備

spec/support/sql_logger.rb
# frozen_string_literal: true

module SqlLogger
  def using_sql_logger
    cached_logger = ActiveRecord::Base.logger
    ActiveRecord::Base.logger = Logger.new($stdout)
    yield
    ActiveRecord::Base.logger = cached_logger
  end
end
spec/rails_helper.rb
...
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

...

RSpec.configure do |config|
...
  config.include SqlLogger
end

課題

subjectをまるっとくくってしまうと、letの遅延評価で呼ばれるクエリも出力されてしまう。
それを回避するために事前にロードしておくようにしたりするのが手間

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?