gpt4 book ai didi

Ruby Double (RR) 如何设置对传递给 block 参数方法的方法调用 block 的期望?

转载 作者:太空宇宙 更新时间:2023-11-03 16:32:35 24 4
gpt4 key购买 nike

在我的代码中,我有类似于以下人为示例的代码。

class Excel
def self.do_tasks
with_excel do |excel|
delete_old_exports
export_images(excel)
export_documents(excel)
end
end

def with_excel
excel = WIN32OLE.connect('Excel.Application')
begin
yield excel
ensure
excel.close()
end
end
end

现在,我想为“do_tasks”方法编写一个测试,我在其中设置对方法调用的期望并查看这些期望是否得到满足。

我尝试了以下方法(使用 shoulda-context 和 test-unit)。然而,最后三个模拟的期望失败了(模拟没有被调用)。

class ExcelTest < ActiveSupport::TestCase  
should "call the expected methods" do
mock.proxy(Excel).with_excel
mock(Excel).delete_old_exports
mock(Excel).export_images.with_any_args
mock(Excel).export_documents.with_any_args

Excel.do_tasks
end
end

任何有关如何测试此类代码的指示都将不胜感激!

最佳答案

一个较旧的问题,但我刚刚用 rr 对一些类似的代码做了一些工作,我想我会给出一个答案。

以下测试将按照您的要求进行(使用 RR 和 TestUnit):

describe Excel do
describe '.do_tasks' do
let(:excel_ole) { mock!.close.subject }

before do
stub(WIN32OLE).connect('Excel.Application') { excel_ole }
mock(Excel).delete_old_exports
mock(Excel).export_images(excel_ole)
mock(Excel).export_documents(excel_ole)
end

it 'calls the expected methods' do
Excel.do_tasks
assert_received(Excel) { |subject| subject.delete_old_exports }
end
end
end

它使用 RR 的“ spy ” double - 参见 https://github.com/rr/rr#spies

但是,对于您提供的示例代码,您要测试的方法位于 block 内这一事实是一个实现细节,不应隐式测试(这可能导致脆弱的测试)。上面的测试表明了这一点,with_excel 方法没有被模拟(顺便说一下,这应该被定义为 self.with_excel 代码才能工作)。可以重构实现,以便 WIN32OLE 初始化和拆卸发生在 .do_tasks 方法中,并且测试仍然会通过。

另一方面,这可能是人为示例的副作用,但通常测试非公共(public)方法不是一个好主意。方法 delete_old_exports、export_images 和 export_documents 看起来应该分解给合作者。

关于Ruby Double (RR) 如何设置对传递给 block 参数方法的方法调用 block 的期望?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13281006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com