簡體   English   中英

Ruby Double(RR)如何為傳遞給塊參數方法的方法調用塊設置期望?

[英]Ruby Double (RR) How do I set up expectations for a block of method calls passed to block argument method?

在我的代碼中,我的代碼類似於以下人為設計的示例。

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”方法編寫一個測試,在其中為方法調用設置期望值,並查看這些期望值是否得到滿足。

我嘗試了以下方法(使用shoda-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的“間諜”雙打-參見https://github.com/rr/rr#spies

但是,對於您提供的示例代碼,您要測試的方法在一個塊內這一事實是實現細節,因此不應進行隱式測試(這可能會導致脆弱的測試)。 上面的測試顯示了這一點,沒有模擬with_excel方法(順便說一句,應該將其定義為self.with_excel才能使代碼正常工作)。 可以重構實現,以便WIN32OLE初始化和拆卸在.do_tasks方法中內聯發生,並且測試仍將通過。

另外,這可能是人為的示例的副作用,但是通常來說,測試非公共方法是個壞主意。 方法delete_old_exports,export_images和export_documents看起來應該被協作者考慮。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM