ruby-on-railsminiteststubs

Minitest stub_any_instance and methods?


If I do

Klass.stub_any_instance(:new, raise(RuntimeError) do
  ...
end

the RuntimeError is raised at the stub_any_instance line and not, as I would like, later when a Klass.new() occurs.

Is there a way to make this work the way I would like?


Solution

  • Wrap the raise in a lambda:

    Klass.stub :new, -> { raise(RuntimeError) } do
      assert_raise { Klass.new }
    end
    

    (You'll also want to use stub rather than stub_any_instance.)