你如何抛出另一个ruby模块的异常?(使用assert_throws)

Daf*_*ees 6 ruby symbols module testunit

我正在尝试编写这样的代码:

assert_throws(:ExtractionFailed) { unit.extract_from('5 x 2005')}
Run Code Online (Sandbox Code Playgroud)

ExtractionFailed是一个简单的子类Exception,并且在test/unit下,我试图断言当我调用unit.extract_from时抛出它(...坏数据......)

我已经ExtractionFailed进入了SemanticText模块,所以现在test/unit说:

<:ExtractionFailed> expected to be thrown but
<:"SemanticText::ExtractionFailed"> was thrown.
Run Code Online (Sandbox Code Playgroud)

我尝试编写assert_throws(:SemanticText :: ExtractionFailed){...},但我得到了相当混乱的消息: TypeError: SemanticText is not a class/module

我可以通过执行以下操作使其工作(虽然它看起来像一个黑客):

  assert_throws(SemanticText::ExtractionFailed.to_s.to_sym) { unit.extract_from('5 x 2005')}
Run Code Online (Sandbox Code Playgroud)

那么在红宝石中说这个断言的正确方法是什么?

mik*_*kej 7

在冒号后面的符号名称周围加上引号,例如

assert_throws(:"SemanticText::ExtractionFailed") { unit.extract_from('5 x 2005')}
Run Code Online (Sandbox Code Playgroud)

对于包含冒号或其他特殊字符的符号,引号是必需的.

如果您尝试:"SemanticText::ExtractionFailed".class使用irb,您将看到它是a Symbol,无需使用to_s和/或to_sym.