1

使用 ruby​​-1.9.3...

我已经阅读了一些关于块和 Procs 主题的规范博客文章,但我不明白为什么这两种情况不同:

module TestHelpers
  def bad_arg_helper(&scenario)

    # this works fine, test passes (without the next line)
    assert_raise ArgumentError, "wrong type of arguments, pass Fixnum or Range parameters", { Myclass.myfunc "bad" }

    # even though the exception is correctly raised in myfunc, this assert does not see it and the test fails
    assert_raise ArgumentError, "wrong type of arguments, pass Fixnum or Range parameters", scenario.call
  end
end

class TestClass < Test::Unit::TestCase
  include TestHelpers

  def test_bad_args
    bad_arg_helper { Myclass.myfunc "bad" }
  end
end

如何将块传递给另一个模块中的测试助手?

4

1 回答 1

2

请查看代码中的三个变体:

require 'test/unit'
class Myclass
  def self.myfunc(par)
    raise ArgumentError unless par.is_a?(Fixnum)
  end
end

module TestHelpers
  def bad_arg_helper(&scenario)

    # this works fine, test passes (without the next line)
    assert_raise( ArgumentError, "wrong type of arguments, pass Fixnum or Range parameters") { Myclass.myfunc "bad" }

    # even though the exception is correctly raised in myfunc, this assert does not see it and the test fails
    assert_raise( ArgumentError, "wrong type of arguments, pass Fixnum or Range parameters", &scenario)
    assert_raise( ArgumentError, "wrong type of arguments, pass Fixnum or Range parameters") { yield }
    assert_raise( ArgumentError, "wrong type of arguments, pass Fixnum or Range parameters") { scenario.call }
  end
end

class TestClass < Test::Unit::TestCase
  include TestHelpers

  def test_bad_args
    bad_arg_helper { Myclass.myfunc "bad" }
  end
end
于 2012-07-01T18:17:43.423 回答