thoughtbot / thoughtbot/factory_bot

Question: Option to disable broadcasts when creating objects via factory_bot

Open
#1,702 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Ruby
Stars
8.2k
Forks
2.6k
PR merge metrics
No merged PRs in 30d

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading FactoryBot::Strategy::Create and the existing suppressing_turbo_broadcasts usage shown in the issue. Determine how a supported option for creating records without broadcasts should fit the existing create flow, and verify that normal create(:my_factory) behavior remains unchanged while the opt-out path suppresses broadcasts.

Written by the indexing model from the issue text.

Assessment

Tech stack
rails, ruby
Domain
testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.