使用 MiniTest 测试方法是否被调用 x 次的更好方法?

Man*_*ijn 5 ruby testing mocking minitest

今天,我从 minitest 的一些基本实现开始,最后找到了一种方法来测试类上的方法是否被调用两次。

在 RSpec 中我会做类似的事情:

expect(@foo).to receive(:some_heavy_calculation).once
2.times { @foo.bar }
Run Code Online (Sandbox Code Playgroud)

现在,我提出了以下 MiniTest 实现,但我不确定这是否是实现此方法的方法,因为 this. 这是我所拥有的

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
Run Code Online (Sandbox Code Playgroud)

我真的必须用模拟来实现这个吗?这将是必须调用 x 次的方法上的主题存根的结果?

小智 4

我不得不做类似的事情。这就是我最终得到的结果...

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
Run Code Online (Sandbox Code Playgroud)