如何解决Rspec:访问Klass.any_instance.stub块中的实例
|Feature: test randomness
In order to make some code testable
As a developer
I want Array#sample to become Array#first
如果可以访问Klass.any_instance.stub块内的实例,则是可能的。像这样:
Array.any_instance.stub(:sample) { instance.first }
但是那afaik是不可能的。
无论如何,需要场景!
解决方法
我找到了一个骇人的解决方案,我已经在rspec 2.13.1和2.14.4版本上对其进行了测试。您将需要2英镑的宝石。
Helper方法-应该可以通过您的rspec示例进行调用:
# must be called inside stubbed implementation
def any_instance_receiver(search_limit = 20)
stack_file_str = \'lib/rspec/mocks/any_instance/recorder.rb:\'
found_instance = nil
# binding_of_caller\'s notion of the stack is different from caller(),so we need to search
(1 .. search_limit).each do |cur_idx|
frame_self,stack_loc = binding.of_caller(cur_idx).eval(\'[self,caller(0)[0]]\')
if stack_loc.include?(stack_file_str)
found_instance = frame_self
break
end
end
raise \"instance not found\" unless found_instance
return found_instance
end
然后在您的示例中:
Array.any_instance.stub(:sample) do
instance = any_instance_receiver
instance.first
end
我为堆栈搜索设置了限制,以避免搜索巨大的堆栈。我不知道您为什么需要增加它,因为它应该始终在5英镑左右。
请注意,在生产中可能不建议使用binding_of_caller
。
, 对于那些现在绊脚石的人,Rspec 3通过传递给stub
的块中的第一个参数实现了此功能:
RSpec::Mocks.configuration.yield_receiver_to_any_instance_implementation_blocks = true # I believe this is the default
Array.any_instance.stub(:sample) { |arr| arr.first }
我在这里找到的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。