在MiniTest的assert_raises/must_raise中,判断异常消息的预期语法是什么?

我试图做出如下断言,其中"Foo"是预期的错误消息:

proc { bar.do_it }.must_raise RuntimeError.new("Foo")

推荐答案

您可以使用assert_raises断言或must_raise期望.

it "must raise" do
  assert_raises RuntimeError do 
    bar.do_it
  end
  ->     { bar.do_it }.must_raise RuntimeError
  lambda { bar.do_it }.must_raise RuntimeError
  proc   { bar.do_it }.must_raise RuntimeError
end

如果需要在错误对象上测试某些内容,可以从断言或预期中获得,如下所示:

describe "testing the error object" do
  it "as an assertion" do
    err = assert_raises RuntimeError { bar.do_it }
    assert_match /Foo/, err.message
  end

  it "as an exception" do
    err = ->{ bar.do_it }.must_raise RuntimeError
    err.message.must_match /Foo/
  end
end

Ruby相关问答推荐

try 安装Chruby时出现问题,终端问题

Ruby注入daisy链?

如何在新行之间拆分字符串并保留空白行?

Ruby:子字符串到一定长度,也到子字符串中的最后一个空格

Integer(value) 和 value.to_i 之间的区别

Ruby数组中的`return`#map

如何获取字符串中所有出现的 Ruby 正则表达式的匹配数据?

将haml标签放入link_to helper

Ruby:module、require和include

文字数字中的下划线是什么意思?

rbenv、rvm 和 chruby 有什么区别?

如何只获取没有命名空间的类名

Ruby 中的=~运算符是什么?

if语句末尾带有then有什么区别?

在类方法中使用实例变量 - Ruby

Ruby - Array#<< 和 Array#push 之间的区别

Ruby Style:如何判断嵌套的哈希元素是否存在

`gem install therubyracer` 在 Mac OS X Lion 上失败

如何在不为 RVM 用户授予 sudo 访问权限的情况下安装 RVM 系统要求

在 Ruby 中解析制表符分隔文件的最佳方法是什么?