[英]How to test a method which uses caller in ruby?
I have a private method which returns something based on the caller method: 我有一个私有方法,该方法根据调用者方法返回一些信息:
private
def aPrivateMethod
r = nil
caller_method = caller[0][/`([^']*)'/, 1]
case caller_method
when "method_1"
r = "I was called by method_1"
when "method_2"
r = "I was called by method_2"
end
return r
end
When writing the test unit the method name calling this private method will not be method_1 nor method_2, it will be something beginning with test and I cannot find a solution to return a pass from the test. 编写测试单元时,调用此私有方法的方法名称将不是method_1也不是method_2,这将是从test开头的内容,我找不到从测试返回通过的解决方案。
Use a regex in the case expression: 在case表达式中使用正则表达式:
def aPrivateMethod
caller_method = caller[0][/`([^']*)'/, 1]
case caller_method
when "method_1"
"I was called by method_1"
when "method_2"
"I was called by method_2"
when /^test_\d+/
"test call from #{caller_method}"
else nil
end
end
Also, you had a lot of superfluous code in there... the r variable is not needed at all. 另外,您那里还有很多多余的代码...根本不需要r变量。
You can create a proxy method in your test class for this purpose 为此,您可以在测试类中创建代理方法。
def method_1 *args
aPrivateMethod *args
end
And then call this method from your test. 然后从您的测试中调用此方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.