diff --git a/README.md b/README.md index 1be07b0..a8e0bd9 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_444 TILs and counting..._ +_445 TILs and counting..._ --- @@ -82,6 +82,7 @@ _444 TILs and counting..._ ### Elixir - [Append To A Keyword List](elixir/append-to-a-keyword-list.md) +- [Assert An Exception Is Raised](elixir/assert-an-exception-is-raised.md) - [Create A Date With The Date Sigil](elixir/create-a-date-with-the-date-sigil.md) - [Execute Raw SQL In An Ecto Migration](elixir/execute-raw-sql-in-an-ecto-migration.md) - [Expose Internal Representation](elixir/expose-internal-representation.md) diff --git a/elixir/assert-an-exception-is-raised.md b/elixir/assert-an-exception-is-raised.md new file mode 100644 index 0000000..b8bc9db --- /dev/null +++ b/elixir/assert-an-exception-is-raised.md @@ -0,0 +1,27 @@ +# Assert An Exception Is Raised + +Elixir's [`ExUnit`](http://elixir-lang.org/docs.html) comes with a number of +different ways to make assertions in your tests. One of those functions is +[`assert_raise`](http://elixir-lang.org/docs/stable/ex_unit/ExUnit.Assertions.html#assert_raise/2) +which allows you to test that a particular exception is raised when the +given function is invoked. + +Using `assert_raise/2` looks something like this: + +```elixir +assert_raise FunctionClauseError, fn -> + Enum.chunk([1,2,3], 0) == [] +end +``` + +The `assert_raise/3` form is also available which allows you to test both +the type of exception and the resulting message. + +```elixir +assert_raise FunctionClauseError, ~r/^no function clause matching/, fn -> + Enum.chunk([1,2,3], 0) == [] +end +``` + +Using the regex sigil for the second argument is generally a good way to go +to keep tests from getting too brittle.