如何使用MiniTest :: Mock测试方法是否被调用

时间:2012-08-19 04:04:05

标签: ruby testing mocking minitest

我想测试一个方法,在本例中是'puts',当我将Foo模块包含到类中并调用'bar'时,会调用它。

require 'minitest/autorun'

module Foo
  def bar
    puts 'bar'
  end
end

class FooTest < MiniTest::Unit::TestCase
  def setup
    @class = Class.new do
      extend Foo
    end
  end

  def test_if_bar_method_calls_puts
    mock = MiniTest::Mock.new
    mock.expect(:puts, nil, ['bar'])
    @class.bar
    assert mock.verify
  end
end

1 个答案:

答案 0 :(得分:3)

你可以这样做:

  def test_if_bar_method_calls_puts
    mock = MiniTest::Mock.new
    mock.expect(:puts, nil, ['bar'])
    @class.stub :puts, -> (arg) { mock.puts arg } do
      @class.bar
    end
    assert mock.verify
  end