Gergo
Gergo

Reputation: 33

Elixir - Using variables in doctest

In my application there is a GenServer, which can create other processes. All process IDs are saved to a list.

def create_process do
    GenServer.call(__MODULE__, :create_process)
end

def handle_call(:create_process, _from, processes) do
    {:ok, pid} = SomeProcess.start_link([])
    {:reply, {:ok, pid}, [pid | processes]}
end

There is also a function to get the list of PIDs.

def get_processes do
    GenServer.call(__MODULE__, :get_processes)
end

def handle_call(:get_processes, _from, processes) do
    {:reply, processes, processes}
end

I tried to write a doctest for the get_processes function like this:

@doc """

    iex> {:ok, pid} = MainProcess.create_process()
    iex> MainProcess.get_processes()
    [pid]

"""

However the test runner doesn't seem to see the pid variable, and I get an undefined function pid/0 error. I know it could be simply solved in with a regular test, but i want to know it it possible to solve in doctest.

Upvotes: 1

Views: 627

Answers (1)

Adam Millerchip
Adam Millerchip

Reputation: 23091

The problem is the [pid] line in your expected result. The expected result should be an exact value, not a variable. You can't reference the variable from the expected result. You can work around it by checking the pid on the previous line:

iex> {:ok, pid} = MainProcess.create_process()
iex> [pid] === MainProcess.get_processes()
true

Upvotes: 2

Related Questions