如何使用 minitest 测试 Ruby catch/throw?

How to test Ruby catch/throw using minitest?

我有一些这样的伪代码:

catch :my_error do
  first_method
  second_method
  third_method
end

def first_method
  if error_condition?
    throw :my_error
  end
end

我正在尝试使用 Minitest 来测试第一个方法是否正确抛出:my_error。我的测试如下所示:

assert_throws :my_error do
  some code in here that ensures error_condition? is true
end

当我 运行 这个测试时,Minitest 没有通过测试:

Minitest::Assertion: Expected :my_error to have been thrown

如果我注释掉 catch :my_error 调用,则测试通过,但当然我需要在生产中使用该代码。不确定 "assert_throws" 的意义是什么,如果它不适用于其中包含捕获的代码。

assert_throws 将断言已抛出某些东西,因此如果它被您的代码捕获,您不能断言已抛出某些东西!

您可以断言一个特定的方法抛出,然后另一个调用这个方法的方法不抛出

或者如果你改变了catch中的任何数据,你可以测试这个数据