How to assert certain method is called with Ruby minitest framework?

steveyang picture steveyang · Jun 3, 2012 · Viewed 22.9k times · Source

I want to test whether a function invokes other functions properly with minitest Ruby, but I cannot find a proper assert to test from the doc.

The source code
class SomeClass
  def invoke_function(name)
    name == "right" ? right () : wrong ()
  end

  def right
    #...
  end

  def wrong
    #...
  end
end
The test code:
describe SomeClass do
  it "should invoke right function" do
    # assert right() is called
  end

  it "should invoke other function" do
    # assert wrong() is called
  end
end

Answer

nas picture nas · Jun 3, 2012

With minitest you use expect method to set the expectation for a method to be called on a mock object like so

obj = MiniTest::Mock.new
obj.expect :right

If you want to set expectation with parameters and return values then:

obj.expect :right, return_value, parameters

And for the concrete object like so:

obj = SomeClass.new
assert_send([obj, :right, *parameters])