Sha256: b1e7691724eb76f27497bbf4b3d7863ef6a26a31e3a0082d29de9c9d51164cbc

Contents?: true

Size: 992 Bytes

Versions: 1

Compression:

Stored size: 992 Bytes

Contents

# frozen_string_literal: true

module RSpec
  module SqlMatcher
    module Helpers
      def count_queries(&block)
        count = 0
        _record_sql_queries(->(_) { count += 1 }, &block)
        count
      end

      def collect_queries(&block)
        queries = []
        _record_sql_queries(->(query) { queries << query }, &block)
        queries
      end

      def log_queries(&block)
        _record_sql_queries(
          lambda { |data|
            puts
            binds = data[:binds].map { |e| "#{e.name} => #{e.value}" }.join(', ')
            puts "#{data[:sql]} | #{binds}"
            puts
            puts
          }, &block
        )
      end

      private

      def _record_sql_queries(callback)
        instance = ActiveSupport::Notifications.subscribe 'sql.active_record' do |_, _, _, _, data|
          callback.call(data)
        end
        yield
      ensure
        ActiveSupport::Notifications.unsubscribe(instance) if instance
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rspec_sql_matcher-0.1.0 lib/rspec/sql_matcher/helpers.rb