Forked from tjchambers/gist:e63fe9e13bef700614780d42f4e326ac
Created
March 10, 2017 23:14
-
-
Save dinjas/b8d5e0a28733051d7886e5406c7d8a5a to your computer and use it in GitHub Desktop.
RSpec query limit tests
This file contains hidden or 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(_, _, _, _, 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From Tim:
"for adding to spec helper
it allows you to create a spec dictating how many sql transaction you expect for a piece of code
I use it to add a expectation for few transactions
like when doing an .include.reference
where mutant wants to remove stuff because it is pure performance enhancement in AR
so I put a spect that runs the block and expects like 1 querey
where mutant would remove the .include
and end up with same result but multiple queries"