如何使用 RSpec 检查一个方法是否调用了另一个方法

How to check that a method has called another method with RSpec

我有以下代码结构(长度缩写):

module Uploader
  def self.execute(folder)
    report_record = Reporting::GenerateReports.call
    establish_api_connection
    upload_file(report_record.first_report, folder)
  end

  def self.upload_file(report, folder)
    upload_content(report.download, "/#{folder}/#{report.filename}")
  end

  def self.upload_content(content, path)
    ...
  end
end

目前,我可以指定在 RSpec 中调用 execute 方法以确保调用 upload_file。但是,我如何模拟检查 upload_file 调用 upload_content?

请记住,expectallowstub 方法调用 - 它们实际上阻止了它 运行。如果你想检查一个方法是否被调用,并且还要确保那个方法调用了另一个方法,你需要使用.and_call_original

# Some setup
folder = "some fake folder" # not sure the data type
report = Reporting::GenerateReports.call
allow(Reporting::GenerateReports).to receive(:call).and_return(stub_report)

# Expectations
expect(Uploader).to receive(:execute).with(some_folder).and_call_original
expect(Uploader).to receive(:upload_file).with(report, folder)

allow(Reporting::GenerateReports) 行是必需的,因为 report_record 变量是在 内部 您的 execute 方法中定义的(无法从通过依赖注入进行测试)。为确保将正确的参数传递给 upload_file,因此需要将其删除。