Unit Tests
Learn about unit-testing macros using the Translator module as an example.
We'll cover the following...
We should use unit-testing macros only for cases where we need to test a tricky code generation in isolation. Over-testing macros at the unit level can lead to brittle tests because we can only test the AST generated from the macro or the string of source produced. These values can be hard to match against and are subject to change, leading to error-prone tests that are difficult to maintain.
The project
Experiment with the following widget. Edit and test the code as guided in the lesson.
ExUnit.start Code.require_file("translator.exs", __DIR__) defmodule TranslatorTest do use ExUnit.Case defmodule I18n do use Translator locale "en", [ foo: "bar", flash: [ notice: [ alert: "Alert!", hello: "hello %{first} %{last}!", ] ], users: [ title: "Users", profile: [ title: "Profiles", ] ]] locale "fr", [ flash: [ notice: [ hello: "salut %{first} %{last}!" ] ]] end test "it recursively walks translations tree" do assert I18n.t("en", "users.title") == "Users" assert I18n.t("en", "users.profile.title") == "Profiles" end test "it handles translations at root level" do assert I18n.t("en", "foo") == "bar" end end
The `TranslatorTest ` module with unit tests
Let’s add unit tests to our ...