How to stub a class method using rspec/rspec-mocks

只谈情不闲聊 提交于 2019-12-04 07:02:38

For your workflow, I think it's going to work better to use a class_double than than to stub the Hashes class directly. allow(Hashes) is always going to require that the Hashes constant is defined. It's simply how Ruby works and RSpec can't do anything about that. With a class double, you can instead do this:

class_double("Hashes", :calculate_hash => canned_return_value).as_stubbed_const

# or

hashes = class_double("Hashes").as_stubbed_const
allow(hashes).to receive(:calculate_hash) do |file|
  # look up what to return
end

class_double("Hashes") provides you with a test double that, when the Hashes constant is defined, will verify the mocked and stubbed methods against the Hashes class definition, but when it is not defined, will act just like a normal double that allows anything to be mocked or stubbed on it. The as_stubbed_const bit tells rspec-mocks to stub the Hashes constant for the duration of the example so that any references to Hashes get your class double rather than the real Hashes class, even if the Hashes class has never been defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!