如何在Ruby中传递一个块来断言_raise?
使用ruby-1.9.3 我读过一些关于blocks&Procs主题的规范博客文章,但我不明白为什么这两种情况不同:如何在Ruby中传递一个块来断言_raise?,ruby,Ruby,使用ruby-1.9.3 我读过一些关于blocks&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 Ran
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
模块测试助手
def bad_arg_帮助程序(&方案)
#这工作正常,测试通过(无下一行)
assert_raise ArgumentError,“参数类型错误,传递Fixnum或Range参数”{Myclass.myfunc“bad”}
#即使在myfunc中正确引发了异常,该断言也看不到异常,测试失败
assert\u raise ArgumentError,“参数类型错误,传递Fixnum或Range参数”,scenario.call
结束
结束
类TestClass
如何将块传递给另一个模块中的测试助手?请参阅代码中的三个变体:
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
要求“测试/单元”
类Myclass
def self.myfunc(par)
除非PAR?ISA A?
结束
结束
模块测试助手
def bad_arg_帮助程序(&方案)
#这工作正常,测试通过(无下一行)
assert_raise(ArgumentError,“参数类型错误,传递Fixnum或范围参数”){Myclass.myfunc“bad”}
#即使在myfunc中正确引发了异常,该断言也看不到异常,测试失败
assert_raise(ArgumentError,“参数类型错误,传递Fixnum或Range参数”,&scenario)
assert_raise(ArgumentError,“参数类型错误,传递Fixnum或范围参数”){yield}
assert_raise(ArgumentError,“参数类型错误,传递Fixnum或范围参数”){scenario.call}
结束
结束
类TestClass
尝试&scenario
而不是scenario。在第二行调用
。成功了。。。我没有看到在参数列表之外使用&
的示例。为什么method.call在这里不起作用?什么时候适合在方法体中使用&
?请随意回答信用问题,并在任何情况下表示感谢。很好的例子。如果我正确理解了语义,对Proc(&scenario
)的引用可以像任何其他变量一样传递到函数中(即括号内),但实际的块不能。我不明白为什么场景。调用可以在花括号内工作。它是否返回块的返回值?scenario.call
调用scenario
并将结果传递给方法。因此,如果没有大括号,就不会返回块,而是返回场景的结果。使用大括号将块传递给方法。在块内部,调用场景
。一个问题是大括号的双重含义:它可以是散列或块。如果没有圆括号,ruby就很难识别哈希或块。