简体   繁体   中英

How to test if method gets called using MiniTest::Mock

I would like to test if a method, in this case 'puts', gets called when I include the Foo module into a class and call '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

You could do something like this:

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM