【问题标题】:Is there a way to unstub in RSpec?有没有办法在 RSpec 中取消存根?
【发布时间】:2013-04-23 17:37:02
【问题描述】:

搜索了 Relish 文档,但没有找到在 RSpec 中取消存根的方法。

这可能吗?

【问题讨论】:

  • 您能解释一下为什么要取消存根吗?也许有更好的方法。

标签: ruby rspec


【解决方案1】:

使用新的expect 语法,unstub 已弃用。你可以这样做:

# stub
allow(SomeClass).to receive(:a_method)

# do something...

# unstub
allow(SomeClass).to receive(:a_method).and_call_original

如果第一个allow 包含.with 或一个块,我相信它仍然会进行到下一个调用,所以下一个allow 不会清除这些东西。

【讨论】:

  • 谢谢。您是否在代码中引用了此文档或位置?
  • 这应该被标记为 rails 4 rspec 3.0 的正确答案
  • 请注意,您可能希望在 ensure(或 after :each)块中执行此操作。
  • 这对我不起作用。当我这样做时,前一个存根仍然存在,并且测试失败,说明“预期:0 次带有任何参数,收到:1 次带有参数:(“Masterfile”)”......
【解决方案2】:

rspec-mock 代码表示可以调用unstub 方法。我引用:

  # Removes a stub. On a double, the object will no longer respond to
  # `message`. On a real object, the original method (if it exists) is
  # restored.
  #
  # This is rarely used, but can be useful when a stub is set up during a
  # shared `before` hook for the common case, but you want to replace it
  # for a special case.
  def unstub(message)
    ::RSpec::Mocks.space.proxy_for(self).remove_stub(message)
  end

【讨论】:

    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多