DEV: Add the 'n_plus_one_control' gem to tests

This gem provides new RSpec matchers helping us to make sure we’re not
creating N+1 queries. It works differently than some other alternatives
as here we don’t have to provide how many queries we expect. The tool
will vary the number of records in the DB and will raise an error
if the number of queries has changed.

A small example has been added in this patch.

Docs at: https://github.com/palkan/n_plus_one_control
This commit is contained in:
Loïc Guitaut 2023-01-26 16:02:54 +01:00
parent 798b4bb604
commit 38933a1694
No known key found for this signature in database
GPG Key ID: 22A453B0123A0403
5 changed files with 16 additions and 3 deletions

View File

@ -147,6 +147,7 @@ group :test do
gem "selenium-webdriver", require: false
gem "test-prof"
gem "webdrivers", require: false
gem "n_plus_one_control"
end
group :test, :development do

View File

@ -234,6 +234,7 @@ GEM
multi_json (1.15.0)
multi_xml (0.6.0)
mustache (1.1.1)
n_plus_one_control (0.6.2)
net-http (0.3.2)
uri
net-imap (0.3.4)
@ -583,6 +584,7 @@ DEPENDENCIES
mocha
multi_json
mustache
n_plus_one_control
net-http
net-imap
net-pop

View File

@ -820,7 +820,7 @@ class TopicView
def find_topic(topic_or_topic_id)
return topic_or_topic_id if topic_or_topic_id.is_a?(Topic)
# with_deleted covered in #check_and_raise_exceptions
Topic.with_deleted.includes(:category, :tags).find_by(id: topic_or_topic_id)
Topic.with_deleted.includes(:category).find_by(id: topic_or_topic_id)
end
def unfiltered_posts

View File

@ -1076,13 +1076,22 @@ RSpec.describe TopicView do
describe "#tags" do
subject(:topic_view_tags) { topic_view.tags }
let(:topic_view) { described_class.new(topic, user) }
let(:topic_view) { described_class.new(topic) }
let(:topic) { Fabricate.build(:topic, tags: tags) }
let(:tags) { Fabricate.build_times(2, :tag) }
let(:user) { Fabricate(:user) }
it "returns the tags names" do
expect(topic_view_tags).to match tags.map(&:name)
end
context "with N+1", :n_plus_one do
let!(:topic) { Fabricate(:topic) }
populate { |n| topic.tags = Fabricate.times(n, :tag) }
specify do
expect { described_class.new(topic.id).tags }.to perform_constant_number_of_queries
end
end
end
end

View File

@ -62,6 +62,7 @@ require "test_prof/before_all/adapters/active_record"
require "webdrivers"
require "selenium-webdriver"
require "capybara/rails"
require "n_plus_one_control/rspec"
# The shoulda-matchers gem no longer detects the test framework
# you're using or mixes itself into that framework automatically.