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 }
但是据我所知这是不可能的。
无论如何,想要场景!
Feature: test randomness
In order to make some code testable
As a developer
I want Array#sample to become Array#first
It would be possible if one could access instance inside Klass.any_instance.stub block. Something like this:
Array.any_instance.stub(:sample) { instance.first }
But that afaik is not possible.
Anyway, scenarios wanted!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了一个 hacky 解决方案,我已经在 rspec 版本 2.13.1 和 2.14.4 上进行了测试。您将需要
binding_of_caller
gem。辅助方法 - 这应该可以由您的 rspec 示例调用:
然后在您的示例中:
我对堆栈搜索设置了限制,以避免搜索巨大的堆栈。我不明白为什么你需要增加它,因为它应该始终在
cur_idx == 8
左右。请注意,在生产中可能不建议使用
binding_of_caller
。I found a hacky solution, which I've tested on rspec versions 2.13.1 and 2.14.4. You'll need the
binding_of_caller
gem.Helper method - this should be callable by your rspec example:
Then in your example:
I've set a limit on the stack searching, to avoid searching a huge stack. I don't see why you'd need to increase it, since it should always be around
cur_idx == 8
.Note that using
binding_of_caller
is probably not recommended in production.对于那些现在遇到这个问题的人,Rspec 3 通过传递给
stub
的块中的第一个参数来实现此功能:我发现了这个
For those stumbling across this now, Rspec 3 implements this functionality via the first argument in the block passed to
stub
:I found this here.