Elixir - How can you use an alias in doctest?
As mentioned by dylanthepiguy it is definitely a better solution to put the aliases into the testfile, just before the doctest
line.
Instrumenting your code for tests is IMHO a code smell.
Also note that as: Submodule
is the default and therefore unnecessary.
Building on the answer from lab419 and dylanthepiguy:
Module with doctest:
defmodule SomeLongModuleName.SubModule do
@doc """
iex> SubModule.add(x, y)
3
"""
def add(x, y) do
x + y
end
end
Test case for module with doctest:
defmodule SomeLongModuleName.SubModuleTest do
use ExUnit.Case, async: true
# Alias the submodule so we don't have to use the fully qualified name
alias SomeLongModuleName.SubModule
doctest SomeLongModuleName.SubModule, import: true
end
There are two ways I can think of to not have to type the module name again and again.
Use interpolation in your docs and use the aliased name:
defmodule SomeLongModuleName.SubModule do alias SomeLongModuleName.SubModule, as: SubModule @doc """ iex> #{SubModule}.method(%{property_a: 1, property_b: 2}) 3 """ def method(%{property_a: a, property_b: b}) do a + b end end
Use just the function name without module and in your call to
doctest
from your tests, addimport: true
:defmodule SomeLongModuleName.SubModule do @doc """ iex> method(%{property_a: 1, property_b: 2}) 3 """ def method(%{property_a: a, property_b: b}) do a + b end end
doctest SomeLongModuleName.SubModule, import: true