简体   繁体   中英

Better way to test if method is called x times with MiniTest?

Today I've started with some basic implementation of minitest and finally figured a way out to test if a method on a class is called twice.

In RSpec I would do something like:

expect(@foo).to receive(:some_heavy_calculation).once
2.times { @foo.bar }

Now, I've came up with the following implementation for MiniTest, but I'm not sure if this is the way to implement this, because this. Here's what I've got

require 'minitest/autorun'

class Foo
  def bar
    @cached_value ||= some_heavy_calculation
  end

  def some_heavy_calculation
    "result"
  end
end

class FooTest < Minitest::Test
  def setup
    @foo = Foo.new
  end

  def cache_the_value_when_calling_bar_twice
    mock = Minitest::Mock.new
    mock.expect(:some_heavy_calculation, [])
    @foo.stub :some_heavy_calculation, -> { mock.some_heavy_calculation } do
      2.times { assert_equal_set @foo.bar, [] }
    end
    mock.verify
  end
end

Do I really have to implement this with a mock, which will be the result of the stub of the subject on the method that has to be called x times?

I had to do something similar. This is what I ended up with...

def cache_the_value_when_calling_bar_twice
  count = 0
  @foo.stub :some_heavy_calculation, -> { count += 1 } do
    2.times { assert_equal_set @foo.bar, [] }
  end
  assert_equal 1, count
end

I did something like this in one of my tests. This also works if your method is potentially invoking multiple instances of a class:

test "verify number of method calls" do
 count = 0
 Foo.stub_any_instance(:some_heavy_calculation, -> { count += 1 }) do
  2.times { assert_equal_set @foo.bar, [] }
 end
 assert_equal 1, count
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