Skip to content

Instantly share code, notes, and snippets.

@jarthod

jarthod/mongo_spy.rb

Created Apr 16, 2021
Embed
What would you like to do?
Ruby module (rspec) to count and assert number of mongo queries
# Examples:
#
# expect { code }.to change { finds("users") }.by(3)
# expect { code }.to change { updates("contents") }.by(1)
# expect { code }.not_to change { inserts }
#
# MongoSpy.flush
# ..code..
# expect(MongoSpy.queries).to match(
# "find" => { "users" => 1, "contents" => 1 },
# "update" => { "users" => 1 }
# )
#
# Reset numbers in a test or before(:each) (optional):
#
# MongoSpy.flush
#
# View all numbers during a test:
#
# pp MongoSpy.queries
#
module MongoSpy
module Helpers
%w(find delete insert update).each do |op|
define_method(op.pluralize) { |ns = nil|
ns ? MongoSpy.queries[op][ns] : MongoSpy.queries[op].values.sum
}
end
end
class << self
def queries
@queries ||= Hash.new { |h, k| h[k] = Hash.new(0) }
end
def flush
@queries = nil
end
def started(event)
op = event.command.keys.first # find, update, delete, createIndexes, etc.
ns = event.command[op] # collection name
return unless ns.is_a?(String)
queries[op][ns] += 1
end
def succeeded(_); end
def failed(_); end
end
end
Mongo::Monitoring::Global.subscribe(Mongo::Monitoring::COMMAND, MongoSpy)
RSpec.configure do |config|
config.include MongoSpy::Helpers
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment