gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:59 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com