【问题标题】:How use minitest/mock for stub calls with expect如何使用 minitest/mock 进行带有期望的存根调用
【发布时间】:2025-12-01 09:05:02
【问题描述】:

参见示例。它不是真正的代码,但显示了问题。 在代码生成器中使用其他参数调用两次。我想检查一个调用 arg install 的调用,并存根其他调用

def test
  bundle_command_mock = Minitest::Mock.new
  bundle_command_mock.expect(:call, nil, ['install'])
  generator.stub(:bundle_command, bundle_command_mock) do |g|
    g.bundle_command('install')
    g.bundle_command('exec spring binstub --all') # <-- This call raise error No more expects available for :call: ["exec spring binstub --all"]
  end

  bundle_command_mock.verify
end

可能吗?我知道那在摩卡咖啡中是可能的。查看 mocha 中的工作示例

def test
  generator.expects(:bundle_command).with('install').once
  generator.stubs(:bundle_command).with('exec spring binstub --all')

  generator.bundle_command("install")
  generator.bundle_command("exec spring binstub --all")
end

【问题讨论】:

    标签: ruby-on-rails mocking minitest


    【解决方案1】:

    存根值仅在块内起作用,因此您可能应该:

    def test
      bundle_command_mock = Minitest::Mock.new
      bundle_command_mock.expect(:call, nil, ['install'])
      generator.stub(:bundle_command, bundle_command_mock) do |g|
        g.bundle_command('install')
        g.bundle_command('exec spring binstub --all') # <-- This call raise error No more expects available for :call: ["exec spring binstub --all"]
      end
    
      bundle_command_mock.verify
    end
    

    【讨论】: