...

/

Smarter Testing with Macros

Smarter Testing with Macros

Learn to create a mini testing framework in Elixir using macros.

If you’re familiar with writing tests in most mainstream languages, you know it can take a while to learn the different assertion functions of testing frameworks.

For example, let’s see how a few basic assertions for popular test frameworks in Ruby and JavaScript compare to Elixir. We don’t need to be familiar with these languages; just be mindful of the different assertion APIs.

Notice how such simple assertions took on arbitrary method and function names in Ruby and JavaScript? They might read nicely, but they subtly mask the expression we are testing. They also require a new mental model for each test framework on how assertions should be made for the given expression.

Press + to interact
#Javascript
expect(value).toBe(true);
expect(value).toEqual(12);
expect(value).toBeGreaterThan(100);
#Ruby
assert value
assert_equal value, 12
assert_operator value, :<=, 100
#Elixir
assert value
assert value == 12
assert value <= 100

The reason these languages require methods and functions like this is to ensure relevant failure messages. If an assertion like assert value <= 100 failed in Ruby, we would only receive a less than helpful “expected true, got false” test output. Ruby can generate correct failure messages by providing unique functions per the assertion, but it comes at the cost of a larger testing API. We also take on the mental overhead of which function is required each time to write an assertion. There’s a better way.

Macros power Elixir’s ExUnit test framework. As we’ve seen, they give us access to the internal representation of any Elixir ...

Access this course and 1400+ top-rated courses and projects.