Skip to content

Instantly share code, notes, and snippets.

@esquinas
Last active January 25, 2024 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esquinas/4afa0b495031872e8fb505933c21209a to your computer and use it in GitHub Desktop.
Save esquinas/4afa0b495031872e8fb505933c21209a to your computer and use it in GitHub Desktop.
Tests N+1 queries in Rails using RSpec
# frozen_string_literal: true
RSpec.describe TestNPlusOnes do
describe "<something>" do
subject(:generate) { puts("<Do something with the DB>") }
# Technique seen in ActiveRecord's #assert_queries_count to use with Minitest:
# https://github.com/rails/rails/blob/0496a5f994f134695bf7bdc02dacdf24925bc67c/activerecord/lib/active_record/testing/query_assertions.rb#L99
it "avoids N+1 queries" do
number_of_queries = 0
counter = ->(*, payload) {
return if payload[:cached]
if payload[:name] != "SCHEMA"
# puts payload[:sql] # This shows the actual query
number_of_queries += 1
end
}
ActiveRecord::Base.connection.materialize_transactions
ActiveSupport::Notifications.subscribed(counter, "sql.active_record") do
generate
expect(number_of_queries).to eq(2)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment