我想存根初始化方法中调用的方法。
有一个Company
这样的类:
class Company
def initialize(code: code, driver: driver)
@driver = driver
@code = code
navigate_to_search_result
end
def navigate_to_search_result
# do something
end
end
而且我想对这个方法存根navigate_to_search_result
。
before(:each) do
company = Company.new(code: 7220, driver: Selenium::WebDriver.for(:phantomjs))
allow(company).to receive(:navigate_to_search_result){ true }
end
但是此代码失败,因为navigate_to_search_result
已经通过初始化执行了。
我该如何存根这样的方法?
在实例化Company
对象之前,即执行操作之前,以下一行之一应在测试中出现/运行Company.new
。
allow_any_instance_of(Company).to receive(:navigate_to_search_result){ true }
或者
allow_any_instance_of(Company).to receive(:navigate_to_search_result).and_return(true)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句