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

标签 ruby module symbols testunit

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

assert_throws(:ExtractionFailed) { unit.extract_from('5 x 2005')}

ExtractionFailedException 的一个简单子(monad)类,在 test/unit 下,我试图断言它在我调用 unit.extract_from(.. . 坏数据...)

我已经将 ExtractionFailed 移动到 SemanticText 模块中,所以现在 test/unit 说:

<:ExtractionFailed> expected to be thrown but
<:"SemanticText::ExtractionFailed"> was thrown.

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

我可以通过执行以下操作使其工作(尽管它看起来像是 hack):

  assert_throws(SemanticText::ExtractionFailed.to_s.to_sym) { unit.extract_from('5 x 2005')}

那么用 ruby​​ 表达这个断言的正确方法是什么?

最佳答案

在冒号后将符号名称用引号引起来,例如

assert_throws(:"SemanticText::ExtractionFailed") { unit.extract_from('5 x 2005')}

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

如果你在 irb 中尝试 :"SemanticText::ExtractionFailed".class 你会看到它是一个 Symbol,不再需要使用 to_s 和/或 to_sym

关于ruby - 你如何断言另一个 ruby​​ 模块的异常被抛出? (使用 assert_throws),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1791350/

相关文章:

ruby-on-rails - validates_length_of :maximum and :minimum on ruby on rails 的自定义错误消息

ruby - 嵌套异常中的回溯

ruby-on-rails - 如何将模型中的元素放入 select_tag

Ruby 继承和重写类方法

linux - 如何提取符号并查看它们在文件中的偏移量

python-3.x - SWIG : fatal error: 'Python.h' file not found

codeigniter hmvc 模块助手

ruby - 如何在 ruby​​ 中引用子模块的 "full path"?

elf - 在 ELF 文件中,_start 的地址是如何确定的?

r - getSymbols.yahoo "method"在 R 中包含多个符号和相应日期的循环中