With the Bullet gem in a Rails app, what three problems does it detect, and how do you make it fail the test suite?
answer
- watches association calls at runtime
- USE / AVOID eager loading messages
- counter cache is the third detector
- Bullet.raise = true in test.rb
- start_request / end_request outside Rack
basics
~10 sBullet watches association access at runtime and reports N+1 queries, unused eager loading and missing counter caches; setting Bullet.raise = true in the test environment makes a detection raise Bullet::Notification::UnoptimizedQueryError and fail the test.
solid answer
~40 sBullet patches Active Record in development and test, records which records were loaded together and which associations the code then reads, and raises three kinds of notice: **USE eager loading** (an N+1: add `.includes(...)`), **AVOID eager loading** (an `includes` the request never used: remove it) and a missing counter cache when `size` or `count` on a has_many queries per record. `bin/rails g bullet:install` writes a `config.after_initialize` block with `Bullet.enable`, `Bullet.alert`, `Bullet.bullet_logger` and friends into development.rb, and can add `Bullet.raise = true` to test.rb, which raises `Bullet::Notification::UnoptimizedQueryError`. Request and system tests are covered by the `Bullet::Rack` middleware; model tests need `Bullet.start_request` and `Bullet.end_request` around each test. Bullet only flags an N+1 when several records were loaded together, so tests need more than one record. Unlike `strict_loading`, it also catches over-eager loading.
code
ruby · 22 lines# config/environments/test.rb
config.after_initialize do
Bullet.enable = true
Bullet.bullet_logger = true
Bullet.raise = true
end
# test/test_helper.rb
module ActiveSupport
class TestCase
def before_setup
Bullet.start_request
super
end
def after_teardown
super
Bullet.perform_out_of_channel_notifications if Bullet.notification?
Bullet.end_request
end
end
endgo deeper
Recall that Bullet flags N+1 queries during development and prints which includes to add.
Name the three detectors, the generator and the test settings, and explain why request tests are covered while model tests need wrapping.
Make Bullet a reliable CI gate: realistic multi-record fixtures, deliberate safelists, and pairing it with strict_loading for hot paths.
Decide what the team enforces in CI versus what is advisory, so query-shape checks block regressions without drowning developers in false positives.
## What Bullet is **Bullet** is a development and test gem that watches how a Rails app uses Active Record associations while requests run, and tells you when the loading strategy is wrong. It is not part of Rails; it hooks into Active Record's loading methods and records two things per request: which records were loaded **together** in one query, and which associations the code then reads on them. ## The three detectors Bullet ships three detectors, all on once `Bullet.enable = true`: | Detector | Notice title | What it means | Usual fix | |---|---|---|---| | N+1 query | `USE eager loading detected` | An association was read lazily on records that were loaded together | Add the association to `includes` / `preload` | | Unused eager loading | `AVOID eager loading detected` | An association was eager loaded but never read | Remove it from the query | | Counter cache | `Need Counter Cache with Active Record size` | `size` or `count` on a has_many ran a COUNT query per record | Add a counter cache column | Each notice names the model and association and, for the first two, prints the exact `Add to your query:` or `Remove from your query:` hint with a call stack. Any detector can be switched off on its own, for example `Bullet.unused_eager_loading_enable = false`, and known false positives can be silenced with `Bullet.add_safelist type: :n_plus_one_query, class_name: "Order", association: :customer`. ## Setting it up 1. Add `gem "bullet"` to the `:development, :test` group of the Gemfile. 2. Run `bin/rails generate bullet:install`. It writes a `config.after_initialize` block into `config/environments/development.rb` with `Bullet.enable`, `Bullet.alert`, `Bullet.bullet_logger` (writes `log/bullet.log`), `Bullet.console`, `Bullet.rails_logger` and `Bullet.add_footer`. 3. Answer yes to the test-environment prompt, or add the block yourself: `Bullet.enable = true`, `Bullet.bullet_logger = true`, `Bullet.raise = true`. ## Making it fail the suite `Bullet.raise = true` makes a detection raise `Bullet::Notification::UnoptimizedQueryError`. Where the check runs matters: - **Integration, request and system tests** pass through the `Bullet::Rack` middleware, which wraps each request in `Bullet.start_request` and `Bullet.end_request`, so they are covered with no extra code. - **Model and other unit tests** never touch Rack. Wrap each test yourself: call `Bullet.start_request` before it, and after it call `Bullet.perform_out_of_channel_notifications if Bullet.notification?` and then `Bullet.end_request`. In Minitest that goes in `before_setup` / `after_teardown` of `ActiveSupport::TestCase`; in RSpec, in `before(:each)` / `after(:each)`. - **Fixture data must have several records.** Bullet marks records as possible N+1 sources only when a query returned more than one of them; a test with a single order never triggers the N+1 detector, however lazy the code is. ## Reading a notice A typical N+1 notice for the wine-shop orders page reads `USE eager loading detected`, then `Order => [:customer]` and `Add to your query: .includes([:customer])`, followed by the call stack that touched the association. The class on the left is the **owner** whose records were loaded together, and the symbol list is the association to add. An unused-eager-loading notice has the same shape with `AVOID eager loading detected` and `Remove from your query:`. Read the call stack before acting: the fix belongs on the relation the controller or query object builds, not in the view that tripped the notice. ## Bullet next to strict_loading | | Bullet | `strict_loading` | |---|---|---| | Where it lives | A gem, development and test | Built into Active Record | | Catches unused eager loads | Yes | No | | Catches missing counter caches | Yes | No | | How it decides | Observed access patterns on records loaded together | Any lazy load on a strict record (or a has_many child in `:n_plus_one_only`) | | Production use | Not intended | `:log` with a subscriber | Teams often run both: `strict_loading` to make lazy loads impossible on hot paths, Bullet to keep `includes` lists from growing stale. The middle-level answer names the three detectors, the `Bullet.raise` setting and its error, and why a one-record test proves nothing.
- A request test for the orders page passes under Bullet.raise, yet production shows per-order customer queries. What is the likeliest cause?The test loaded a single order. Bullet treats a record as a possible N+1 source only when it came from a query that returned several records, so one fixture order never triggers the detector. Seed at least two orders with different customers in that test.
- Bullet reports AVOID eager loading on includes(:line_items), but the show view does read line items. Why might that happen?Usually a different path reads them: the view calls a scoped query such as `order.line_items.where(...)`, which runs its own query and never touches the loaded association, so the eager load really is unused. Read the loaded collection instead, or drop the `includes`. Only safelist it when the read genuinely happens in code Bullet cannot see.
- Bullet ships with Rails and runs in production by default
- Bullet.alert = true is what makes tests fail
- Bullet only detects N+1 queries
- A test with one order record is enough to catch an N+1
- Model tests are covered automatically by Bullet::Rack