有没有办法在RSpec取消存根?

B S*_*ven 38 ruby rspec

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

这可能吗?

ela*_*ado 98

使用新expect语法时,unstub不推荐使用.你可以做:

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

# do something...

# unstub
allow(SomeClass).to receive(:a_method).and_call_original
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你.您是否在代码中引用了此文档或位置? (2认同)
  • 这应该标记为rails 4 rspec 3.0的正确答案 (2认同)

fme*_*dez 24

RSpec中,模拟代码表明您可以调用的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
Run Code Online (Sandbox Code Playgroud)