【问题标题】:How to replace stub with double?如何用双替换存根?
【发布时间】:2015-02-18 22:40:44
【问题描述】:

我想测试一个包含MessageMailer.message_notification(self).deliver 方法的方法。 MessageMailer 有点慢,而且我正在编写的测试没有测试它,所以我希望交付不在测试块中运行。

目前,我正在通过 stubing 来实现这一点。

before do
  mail = double('email', deliver: true)
  MessageMailer.stub(:message_notification) { mail }
end

但我听说 stub 将来会被 double 取代,并且 MessageMailer.double(:message_notification) 在我的 Rspec (2.12.2) 版本中失败并出现 NoMethodError for double 。我应该如何用 double 重写此代码以防止调用 Deliver 方法?

【问题讨论】:

    标签: rspec stubbing


    【解决方案1】:

    您可以使用allow,如“方法存根”下的https://relishapp.com/rspec/rspec-mocks/v/3-1/docs 所述:

    before do
      mail = double('email', deliver: true)
      allow(MessageMailer).to receive(:message_notification) { mail }
    end
    

    您也可以使用receive_message_chain,如https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains 中所述:

    before { allow(MessageMailer).to receive_message_chain(:message_notification, :deliver => true) }
    

    但请注意有关得墨忒耳定律、脆性等的相关警告。

    【讨论】:

      猜你喜欢
      • 2016-08-10
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      相关资源
      最近更新 更多