如何在Ruby单元测试中Assert错误消息?

pokxtpni  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(170)

在Ruby on Rails项目中,我希望在代码中对异常消息进行Assert,以确保它由于正确的原因失败,并提到重要的细节。
下面是一个总是引发的函数:

class Quiz < ApplicationRecord
  def self.oops
    raise ArgumentError.new("go away")
  end
end

测试:

require "test_helper"

class QuizTest < ActiveSupport::TestCase
  test "error message" do
    assert_raises(ArgumentError, match: /whatever/) do
      Quiz.oops()
    end
  end
end

当我运行bin/rake test时,这通过了,但我预计它会失败,因为实际的错误消息与assert_raises中的match不匹配。
如何捕获错误消息并针对它进行Assert?

dxxyhpgq

dxxyhpgq1#

我认为你可以使用一种稍微不同的方法(使用块捕获错误消息,然后对消息内容进行Assert):

test "error message" do
  exception = assert_raises(ArgumentError) do
    Quiz.oops()
  end
  assert_match(/whatever/, exception.message)
end

相关问题