Skip to content

Instantly share code, notes, and snippets.

@tjchambers
Last active March 10, 2017 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tjchambers/e63fe9e13bef700614780d42f4e326ac to your computer and use it in GitHub Desktop.
Save tjchambers/e63fe9e13bef700614780d42f4e326ac to your computer and use it in GitHub Desktop.
RSpec query limit tests
# From http://stackoverflow.com/a/13423584/153896
module ActiveRecord
class QueryCounter
attr_reader :query_count
def initialize
@query_count = 0
end
def to_proc
lambda(&method(:callback))
end
def callback(_, _, _, _, values)
@query_count += 1 unless %w(CACHE SCHEMA).include?(values[:name])
end
end
end
# Derived from http://stackoverflow.com/a/13423584/153896. Updated for RSpec 3.
RSpec::Matchers.define :exceed_query_limit do |expected|
supports_block_expectations
match do |block|
query_count(&block) > expected
end
failure_message_when_negated do
"Expected to run maximum #{expected} queries, got #{@counter.query_count}"
end
def query_count(&block)
@counter = ActiveRecord::QueryCounter.new
ActiveSupport::Notifications.subscribed(@counter.to_proc, 'sql.active_record', &block)
@counter.query_count
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment