Disable specific callback in spec

Augusts Bautra - May 16 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .