2016-12-20 09:48:04 -05:00
|
|
|
module ActiveRecord
|
|
|
|
class QueryRecorder
|
2017-04-04 17:52:59 -04:00
|
|
|
attr_reader :log, :cached
|
2016-12-20 09:48:04 -05:00
|
|
|
|
|
|
|
def initialize(&block)
|
|
|
|
@log = []
|
2017-04-04 17:52:59 -04:00
|
|
|
@cached = []
|
2016-12-20 09:48:04 -05:00
|
|
|
ActiveSupport::Notifications.subscribed(method(:callback), 'sql.active_record', &block)
|
|
|
|
end
|
|
|
|
|
|
|
|
def callback(name, start, finish, message_id, values)
|
2017-04-04 17:52:59 -04:00
|
|
|
if values[:name]&.include?("CACHE")
|
|
|
|
@cached << values[:sql]
|
|
|
|
elsif !values[:name]&.include?("SCHEMA")
|
|
|
|
@log << values[:sql]
|
|
|
|
end
|
2016-12-20 09:48:04 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def count
|
|
|
|
@log.count
|
|
|
|
end
|
|
|
|
|
2017-04-04 17:52:59 -04:00
|
|
|
def cached_count
|
|
|
|
@cached.count
|
|
|
|
end
|
|
|
|
|
2016-12-20 09:48:04 -05:00
|
|
|
def log_message
|
|
|
|
@log.join("\n\n")
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
RSpec::Matchers.define :exceed_query_limit do |expected|
|
|
|
|
supports_block_expectations
|
|
|
|
|
|
|
|
match do |block|
|
|
|
|
query_count(&block) > expected
|
|
|
|
end
|
|
|
|
|
|
|
|
failure_message_when_negated do |actual|
|
|
|
|
"Expected a maximum of #{expected} queries, got #{@recorder.count}:\n\n#{@recorder.log_message}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def query_count(&block)
|
|
|
|
@recorder = ActiveRecord::QueryRecorder.new(&block)
|
|
|
|
@recorder.count
|
|
|
|
end
|
|
|
|
end
|