[英]Stubbing method parameters in RSpec
Suppose I have a class 假设我有一堂课
class A
def initialize
end
def foo(a, b)
# Do stuff
end
end
When writing RSpec tests for this, how do I intercept the call to foo
and modify it's parameters? 为此编写RSpec测试时,如何截获对foo
的调用并修改其参数?
I might try something like the following that catches the method call, yields the params so I can modify them, and then calls the original method 我可能会尝试以下类似方法来捕获方法调用,产生参数,以便我可以对其进行修改,然后调用原始方法
my_obj = A.new
allow(my_obj).to receive(:foo) do |a, b|
my_obj.foo("new", "values")
end
expect(my_obj.foo).to eq("bar")
However, the problem with this is that calling A#foo
inside the block once again stubs that and yields a new block, producing an infinite recursive loop until the stack runs out of memory. 但是,这样做的问题在于,再次在该块内调用A#foo
存根并生成一个新块,从而产生无限递归循环,直到堆栈用尽内存。
I know that .and_call_original
method also exists, but can I yield the params with that and modify them before calling the original with the new modified params? 我知道.and_call_original
方法也存在,但是我可以使用该方法产生参数并在使用新的已修改参数调用原始参数之前对其进行修改吗?
Or is there a way to "un-stub" the object inside the block so me calling it again doesn't cause a problem? 还是有一种方法可以“取消存根”块中的对象,以便我再次调用它不会引起问题?
Thanks! 谢谢!
Use and_wrap_original
: 使用and_wrap_original
:
my_obj = A.new
allow(my_obj).to receive(:foo).and_wrap_original do |original_method, a, b|
original_method.call("new", "values")
end
expect(my_obj.foo).to eq("bar")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.