Last active
January 25, 2024 15:40
-
-
Save esquinas/4afa0b495031872e8fb505933c21209a to your computer and use it in GitHub Desktop.
Tests N+1 queries in Rails using RSpec
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
# 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