Created
July 7, 2014 14:40
-
-
Save rsutphin/af06c9e3dadf658d2293 to your computer and use it in GitHub Desktop.
RSpec 3 matcher for ActiveRecord query count limits. Based on http://stackoverflow.com/a/13423584/153896.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |actual| | |
"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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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(name, start, finish, message_id, values) | |
@query_count += 1 unless %w(CACHE SCHEMA).include?(values[:name]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
What license is this code released under?
Thanks!