Search code examples
elixirdoctestex-unit

How do I write an Elixir doctest to verify an empty MapSet


Just learning about doctests in Elixir and I'm trying to write an Elixir doctest to verify that a struct will contain two empty MapSets.

defstruct [:coordinates, :hit_coordinates]

@doc """
  Creates a new Island structure

  ## Examples

    iex> IslandsEngine.Island.new()
    %IslandsEngine.Island { coordinates: #MapSet<[]>, hit_coordinates: #MapSet<[]> }

"""
def new(), do:
  %Island{ coordinates: MapSet.new(), hit_coordinates: MapSet.new() }

When I run this using mix test I get the following error:

Compiling 1 file (.ex)

  1) doctest IslandsEngine.Island.new/0 (1) (IslandsEngine.IslandTest)
     test/islands_engine/island_test.exs:3
     Doctest did not compile, got: (TokenMissingError) lib/islands_engine/island.ex:19: missing terminator: } (for "{" starting at line 19)
     code: %IslandsEngine.Island { coordinates: #MapSet<[]>, hit_coordinates: #MapSet<[]> }
     stacktrace:
       lib/islands_engine/island.ex:19: IslandsEngine.Island (module)

.......

Finished in 0.1 seconds
6 doctests, 2 tests, 1 failure

Yet all runs fine in IEx session:

iex> IslandsEngine.Island.new()
%IslandsEngine.Island{coordinates: #MapSet<[]>, hit_coordinates: #MapSet<[]>}
iex>

Thanks for any help!


Solution

  • You need to have code constructing a valid answer instead of the textual representation in your doctest. So instead of:

    %IslandsEngine.Island{coordinates: #MapSet<[]>, hit_coordinates: #MapSet<[]>}
    

    Do:

    %IslandsEngine.Island{coordinates: %MapSet{}, hit_coordinates: %MapSet{}}
    

    I guess in this case the example has little value as a test, because it just replicates the code, but it might still be valid as documentation.