What is the expected syntax for checking exception messages in MiniTest's assert_raises/must_raise?

后端 未结 4 1264
粉色の甜心
粉色の甜心 2020-12-25 09:39

What is the expected syntax for checking exception messages in MiniTest\'s assert_raises/must_raise?

I\'m trying to make an assertion somet

4条回答
  •  鱼传尺愫
    2020-12-25 10:06

    Minitest does not provide (yet) you a way to check the actual exception message. But you could add a helper method that does it and extend ActiveSupport::TestCase class to use everywhere in your rails test suite, e.g.: in test_helper.rb

    class ActiveSupport::TestCase
      def assert_raises_with_message(exception, msg, &block)
        block.call
      rescue exception => e
        assert_match msg, e.message
      else
        raise "Expected to raise #{exception} w/ message #{msg}, none raised"
      end
    end
    

    and use it in your tests like:

    assert_raises_with_message RuntimeError, 'Foo' do
      code_that_raises_RuntimeError_with_Foo_message
    end
    

提交回复
热议问题