Skip to content

Instantly share code, notes, and snippets.

@kennyadsl
Created January 2, 2019 14:05
Show Gist options
  • Save kennyadsl/4443c3bce12e8d2ef2eb0740d61d2344 to your computer and use it in GitHub Desktop.
Save kennyadsl/4443c3bce12e8d2ef2eb0740d61d2344 to your computer and use it in GitHub Desktop.
Query count RSpec
https://blog.arkency.com/two-ways-for-testing-preloading-eager-loading-of-activerecord-association-in-rails/
https://github.com/monterail/rspec-query-limit
# Create a new file: api/spec/support/query_count_matcher.rb
# frozen_string_literal: true
RSpec::Matchers.define :query_limit_eq do |expected|
match do |block|
query_count(&block) == expected
end
if respond_to?(:failure_message)
failure_message do |_actual|
failure_text
end
failure_message_when_negated do |_actual|
failure_text_negated
end
else
failure_message_for_should do |_actual|
failure_text
end
failure_message_for_should_not do |_actual|
failure_text_negated
end
end
def query_count(&block)
@counter = 0
counter = ->(_name, _started, _finished, _unique_id, payload) {
unless %w[CACHE SCHEMA].include?(payload[:name])
@counter += 1
end
}
ActiveSupport::Notifications.subscribed(
counter,
"sql.active_record",
&block
)
@counter
end
def supports_block_expectations?
true
end
def failure_text
"Expected to run exactly #{expected} queries, got #{@counter}"
end
def failure_text_negated
"Expected to run other than #{expected} queries, got #{@counter}"
end
end
# Adding this specs into api/spec/requests/spree/api/taxons_controller_spec.rb:87
context 'filtering by taxon ids' do
let!(:v2_4) { create(:taxon, name: "2.4", parent: taxon, taxonomy: taxonomy) }
let!(:v2_4_1) { create(:taxon, name: "2.4.1", parent: v2_4, taxonomy: taxonomy) }
it 'returns only requested ids' do
get spree.api_taxons_path, params: { ids: [v2_4_1.id] }
expect(json_response['taxons'].size).to eq 1
end
it 'avoids N+1 queries retrieving several taxons' do
expect {
get spree.api_taxons_path, params: { ids: [v2_4.id, v2_4_1.id] }
}.to query_limit_eq(7)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment