我的代码结构如下(因篇幅而简略)。
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
目前,我可以规范调用 execute
方法,以确保RSpec中的 upload_file
被调用。 然而,我怎样才能模拟检查出 upload_file
电话 upload_content
?
记住 expect
和 allow
两者 存根 方法的调用--它们会阻止它实际运行。如果你想检查这一个方法是否被调用,并确保 该 方法调用另一个方法,你需要使用 .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
因此,它需要被捅掉。