Search code examples
elixirex-unit

ExUnit Assertions


In the test cases we use assertions to handle errors. Match their return value with what we defined and the test will pass. like if we have an argument error we use this:

 assert_raise ArgumentError, "argument error", fn ->

This will work and test will pass. If we have ArgumentError. Same is the case with RuntimeError

But if we have long error messages like this:

 exception Postgrex.Error (ERROR 42703 (undefined_column): column 
 j0.rating does not exist)

How can we handle these kind of long exception messages in our test cases?

Thanks


Solution

  • If you don't want to assert the message inside the exception, you can call assert_raise/2:

    assert_raise Postgrex.Error, fn ->
      ...
    end
    

    If you want to only match a part of the exception message, you can pass a regex to assert_raise/3:

    assert_raise Postgrex.Error, ~r/undefined_column/, fn ->
      ...
    end