1

我有一个私有方法,它根据调用者方法返回一些东西:

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

在编写测试单元时,调用此私有方法的方法名称不会是 method_1 也不是 method_2,它将是以 test 开头的东西,我找不到从测试返回通过的解决方案。

4

2 回答 2

0

在 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

此外,您那里有很多多余的代码......根本不需要 r 变量。

于 2012-08-16T14:22:27.753 回答
0

为此,您可以在测试类中创建代理方法

def method_1 *args
  aPrivateMethod *args
end

然后从您的测试中调用此方法。

于 2012-08-16T14:27:22.307 回答