如何测试在ruby中使用调用者的方法?

时间:2012-08-16 08:21:48

标签: ruby unit-testing

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

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开头,我找不到从测试中返回传递的解决方案。

2 个答案:

答案 0 :(得分:0)

在案例表达式中使用正则表达式:

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变量。

答案 1 :(得分:0)

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

def method_1 *args
  aPrivateMethod *args
end

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