How to ignore Bullet in RSpec tests

Using Bullet during a test can pick up mistakes but also has false negatives; here is an easy way to ignore them

The Bullet gem is an excellent tool for finding opportunities to improve how you grab data via ActiveRecord. On a recent project, we’ve been running Bullet in our test environment as well as development. It has helped us find some improvements to areas of the app we rarely hit when developing new features.

Occasionally Bullet will shout about a potential N+1 query that, for any number of reasons you know to be false. Most commonly for us, it is that the minimal test data used doesn’t reflect what happens in the system.

We could update the tests to do more setup, but slowing down our test suite doesn’t feel great, especially if that means some tests have more setup to read through that don’t add value to the thing under test.

We decided to introduce a quick flag into the tests that tell Bullet to skip its check.

In our rails_helper.rb file (you can use whichever RSpec config file makes the most sense), we added;

config.before(:each, bullet: :skip) do
  Bullet.enable = false
end

config.after(:each, bullet: :skip) do
  Bullet.enable = true
end

These two blocks check for scenarios with bullet: :skip, and if they find one before they run tests, they will set Bullet.enable to false and then set it back to true after.

Then on any test that we didn’t want Bullet to run, we add;

scenario 'A user signs in to comment', bullet: :skip do
  # some test code
end

The nice thing about this approach is you can comment out the config.before action and run your suite to see which skipped Bullet runs are failing. Doing this will let you double-check you haven’t introduced a genuine issue in that code under test.


Recent posts View all

Ruby

Using Faker with Rails

A guide to setting up Faker to work within Rails and why you'd want to

Freelancing

Things our micro business does

Here are some of the things that we do as a micro business