14

Is there any way to verify a method never called or only a number of times called using Minitest::Mock

Thanks in advance

Rnk Jangir
  • 711
  • 6
  • 23

2 Answers2

15

Specific number of times: Minitest::Mock forces the developer to be explicit about message expectations, so if you expect a given method to be called x times, you'll need to be very literal about it.

my_mock = Minitest::Mock.new
x.times { my_mock.expect :some_method, :return_val }

Never called: Philosophically, Minitest shies away from testing that something doesn't happen. While it's not completely analogous, have a look at this post or google "minitest assert nothing raised".

Minitest::Mock will raise a NoMethodError whenever an unexpected method is called on it. That's not exactly an assertion, but probably has the desired effect. Still, you don't particularly need a mock to do what you're asking. You can do the same by patching your real object instance.

def test_string_size_never_called
  str = "foo"
  def str.size
    raise NoMethodError, "unexpected call"
  end

  # test logic continues...
end
GMA
  • 5,816
  • 6
  • 51
  • 80
Chris Kottom
  • 1,249
  • 10
  • 11
  • For x times, how will we verify that method is only called exactly x times not x+1 times? – Rnk Jangir May 26 '15 at 17:23
  • 1
    Because when you call your method for the n+1-th time, you'll get a MockExpectationError. See the following gist: https://gist.github.com/chriskottom/b9a73eaffb2c5b5b6676 – Chris Kottom May 27 '15 at 06:33
2

Was looking for a "proper" way to test that something isn't called in minitest (I hate minitest) and stumbled upon this question.

I ended up doing it like this:

def test_foo_isnt_called
  Foo.stub(:call, proc { raise "shouldn't happen" }) do
    subject(x, y)
  end
end
Nondv
  • 769
  • 6
  • 11