Error when testing filtering eager loaded data in Rails 7

220 Views Asked by At

Currently in my index action I load the data as:

posts.includes([:user, :status])

Note: Posts belongs to a user optionally. There are posts that have no user.

And then I'm filtering those posts based on different params. Everything worked perfectly until I was trying to filter the posts that have no user.

scope :no_user, -> { where(user_id: nil) }

Theres is no error showing up when I try to test the behaviour in the browser but my controller tests (Minitest) are failing when the GET request is made with this particular filter.

Bullet::Notification::UnoptimizedQueryError
AVOID eager loading detected
  Post => [:user]
  Remove from your query: .includes([:user])

The funny part is when I remove the :user from the array, I get the exact opposite error on the other filter tests.

USE eager loading detected
  Post => [:user]
  Add to your query: .includes([:user])

Note: I get the same error if I try to use left_outer_joins(:user)

Is there a way to remove this error in tests without a conditional statement only for this particular filter?

1

There are 1 best solutions below

0
On

I found the fix myself for the moment by just adding in config/environments/test.rb the following:

  config.after_initialize do
    Bullet.add_safelist type: :unused_eager_loading, class_name: "Post", association: :user
  end