Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

n_plus_one_control

> 数据库
Open source

RSpec and Minitest matchers to prevent N+1 queries problem

580 stars0 likes1 views
WebsiteGitHub

About

RSpec and Minitest matchers to prevent N+1 queries problem

N + 1 Control

RSpec and Minitest matchers to prevent the N+1 queries problem.

Why yet another gem to assert DB queries?

Unlike other libraries (such as db-query-matchers, rspec-sqlimit, etc), with n_plus_one_control you don't have to specify exact expectations to control your code behaviour (e.g. expect { subject }.to query(2).times).

Such expectations are rather hard to maintain, 'cause there is a big chance of adding more queries, not related to the system under test.

NPlusOneControl works differently. It evaluates the code under consideration several times with different scale factors to make sure that the number of DB queries behaves as expected (i.e. O(1) instead of O(N)).

So, it's for performance testing and not feature testing.

Read also "Squash N+1 queries early with n_plus_one_control test matchers for Ruby and Rails".

Why not just use bullet?

Of course, it's possible to use Bullet in tests (see more here), but it's not a silver bullet: there can be both false positives and true negatives.

This gem was born after I've found myself not able to verify with a test yet another N+1 problem.

N+1 Control is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.

Installation

Add this line to your application's Gemfile:

ruby
group :test do
  gem "n_plus_one_control"
end

And then execute:

$ bundle

Usage

RSpec

First, add NPlusOneControl to your spec_helper.rb:

ruby
# spec_helper.rb
require "n_plus_one_control/rspec"

Then:

ruby
# Wrap example into a context with :n_plus_one tag
context "N+1", :n_plus_one do
  # Define `populate` callbacks which is responsible for data
  # generation (and whatever else).
  #
  # It accepts one argument – the scale factor (read below)
  populate { |n| create_list(:post, n) }

  specify do
    expect { get :index }.to perform_constant_number_of_queries
  end
end

NOTE: do not use memoized values within the expectation block!

…

Availables modifiers:

ruby
# You can specify the RegExp to filter queries.
# By default, it only considers SELECT queries.
expect { get :index }.to perform_constant_number_of_queries.matching(/INSERT/)

# You can also provide custom scale factors
expect { get :index }.to perform_constant_number_of_queries.with_scale_factors(10, 100)

# You can specify the exact number of expected queries
expect { get :index }.to perform_constant_number_of_queries.exactly(1)

Using scale factor in spec

Let's suppose your action accepts parameter, which can make impact on the number of returned records:

ruby
get :index, params: {per_page: 10}

Then it is enough to just change per_page parameter between executions and do not recreate records in DB. For this purpose, you can use current_scale method in your example:

ruby
context "N+1", :n_plus_one do
  before { create_list :post, 3 }

  specify do
    expect { get :index, params: {per_page: current_scale} }.to perform_constant_number_of_queries
  end
end

Expectations in execution block

Both rspec matchers allows you to put additional expectations inside execution block to ensure that tested piece of code actually does what expected.

ruby
context "N+1", :n_plus_one do
  specify do
    expect do
      expect(my_query).to eq(actuall_results)
    end.to perform_constant_number_of_queries
  end
end

Other available matchers

perform_linear_number_of_queries(slope: 1) allows you to test that a query generates linear number of queries with the given slope.

ruby
context "when has linear query", :n_plus_one do
  populate { |n| create_list(:post, n) }

  specify do
    expect { Post.find_each { |p| p.user.name } }
      .to perform_linear_number_of_queries(slope: 1)
  end
end

Minitest

First, add NPlusOneControl to your test_helper.rb:

ruby
# test_helper.rb
require "n_plus_one_control/minitest"

Then use assert_perform_constant_number_of_queries assertion method:

ruby
def test_no_n_plus_one_error
  populate = ->(n) { create_list(:post, n) }

  assert_perform_constant_number_of_queries(populate: populate) do
    get :index
  end
end

You can also use assert_perform_linear_number_of_queries to test for linear queries:

ruby
def test_no_n_plus_one_error
  populate = ->(n) { create_list(:post, n) }

  assert_perform_linear_number_of_queries(slope: 1, populate: populate) do
    Post.find_each { |p| p.user.name }
  end
end

You can also specify custom scale factors or filter patterns:

ruby
assert_perform_constant_number_of_queries(
  populate: populate,
  scale_factors: [2, 5, 10]
) do
  get :index
end

assert_perform_constant_number_of_queries(
  populate: populate,
  matching: /INSERT/
) do
  do_some_havey_stuff
end

For the constant matcher, you can also specify the expected number of queries as the first argument:

ruby
assert_perform_constant_number_of_queries(2, populate: populate) do
  get :index
end

It's possible to specify a filter via NPLUSONE_FILTER env var, e.g.:

ruby
NPLUSONE_FILTER = users bundle exec rake test

You can also specify populate as a test class instance method:

ruby
def populate(n)
  create_list(:post, n)
end

def test_no_n_plus_one_error
  assert_perform_constant_number_of_queries do
    get :index
  end
end

As in RSpec, you can use current_scale factor instead of populate block:

ruby
def test_no_n_plus_one_error
  assert_perform_constant_number_of_queries do
    get :index, params: {per_page: current_scale}
  end
end

With caching

If you use caching you can face the problem when first request performs more DB queries than others. The solution is:

…

If your warmup and testing procs are identical, you can use:

ruby
expect { get :index }.to perform_constant_number_of_queries.with_warming_up # RSpec only

Configuration

There are some global configuration parameters (and their corresponding defaults):

…

How does it work?

Take a look at our Executor to figure out what's under the hood.

What's next?

  • More matchers.

It may be useful to provide more matchers/assertions, for example:

ruby

# Actually, that means that it is N+1))
assert_linear_number_of_queries { some_code }

# But we can tune it with `coef` and handle such cases as selecting in batches
assert_linear_number_of_queries(coef: 0.1) do
  Post.find_in_batches { some_code }
end

# probably, also make sense to add another curve types
assert_logarithmic_number_of_queries { some_code }
  • Support custom non-SQL events.

N+1 problem is not a database specific: we can have N+1 Redis calls, N+1 HTTP external requests, etc. We can make n_plus_one_control customizable to support these scenarios (technically, we need to make it possible to handle different payload in the event subscriber).

If you want to discuss or implement any of these, feel free to open an issue or propose a pull request.

Development

bash
# install deps
bundle install

# run tests
bundle exec rake

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/palkan/n_plus_one_control.

License

The gem is available as open source under the terms of the MIT License.

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubydatabase-testinghacktoberfestminitestperformance-testing

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库