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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

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?

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More