Reputation: 741
Is there any way to verify a method never called or only a number of times called using Minitest::Mock
Thanks in advance
Upvotes: 16
Views: 7321
Reputation: 819
Was looking for a "proper" way to test that something isn't called in 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
Upvotes: 4
Reputation: 1289
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
Upvotes: 17