bullet icon indicating copy to clipboard operation
bullet copied to clipboard

Rails: Allow manually handling requests (especially for testing)

Open davidwessman opened this issue 5 years ago • 2 comments

Background

I am working through our test-suite to add bullet, I cannot turn it on for all tests and therefore want to turn it on manually per test case. It works great with Bullet.raise = true, but I would like to get all warnings at once, therefore I tried using a solution based on kerrizor's solution and it looks like:

module BulletTesting
  def bullet_setup
    Bullet.enable = true
    Bullet.bullet_logger = true
    Bullet.start_request
  end

  def bullet_teardown
    # With a Rack-request it has already called `Bullet.end_request` here.
    return unless Bullet.start?

    Bullet.perform_out_of_channel_notifications if Bullet.notification?
    if Bullet.warnings.present?
      warnings = Bullet.warnings.map { |_k, warning| warning }.flatten.map { |warn| warn.body_with_caller }.join("\n-----\n\n")

      flunk(warnings)
    end
    Bullet.end_request
    Bullet.enable = false
    Bullet.reset_whitelist
  end
end

It works great for ActionController::TestCase, but for ActionDispatch::IntegrationTest the request has always ended when I reach the bullet_teardown method because Bullet.end_request has been called in lib/bullet/rack.rb#call.

Questions

  1. Is there anyway for me to disable the rack-integration?
  2. Would it make sense with an option to disable internal calls to start_request and end_request? Maybe Bullet.manual_requests = true?

Thank you!

davidwessman avatar Jan 28 '21 14:01 davidwessman

I have a similar use case.

As a workaround I added the following to config/environments/test.rb

config.middleware.delete Bullet::Rack

guigs avatar May 10 '21 16:05 guigs

It's not entirely the same, but for selective usage I'm using this:

  RSpec.configure do |config|
    config.before(:each, :use_bullet_detectors) do
      Bullet.start_request
    end

    config.after(:each, :use_bullet_detectors) do
      Bullet.perform_out_of_channel_notifications if Bullet.notification?
      Bullet.end_request
    end
  end

and then tagging the describe|context|it with :use_bullet_detectors.

bogn83 avatar May 31 '22 06:05 bogn83