DEV Community

Augusts Bautra
Augusts Bautra

Posted on • Edited on

2

Disable specific callback in spec

Sometimes a service is called in some after_commit callback and it triggers already during setup in that service spec as we're trying to get to arguments for the service (usually some record ids).

If only there was a way to disable the callback...

There is! Override the callback method for the one spec instance:

# important to :build so the after-save/commit callback we want to disable does not trigger yet
let(:model_instance) { build(:my_model) }

before do
  model_instance.private_methods.include?(:some_callback) ||  
    # some safety if the callback gets renamed or removed
    raise(":some_callback missing!")

  def model_instance.some_callback
    nil
  end

  model_instance.save!
end
Enter fullscreen mode Exit fullscreen mode

More on singleton redefinition in SO thread.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
sawyerwolfe profile image
Sawyer Wolfe

This is a neat approach! Have you tried using any other methods to disable callbacks, and how did they compare to this one?

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more