Skip to content

Instantly share code, notes, and snippets.

@smdern
Created June 14, 2016 03:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smdern/105f5d2a4a40983838faeaf4db4e2813 to your computer and use it in GitHub Desktop.
Save smdern/105f5d2a4a40983838faeaf4db4e2813 to your computer and use it in GitHub Desktop.
meck + gproc spike
defmodule StubbedModule do
def get_state do
"ACTUAL MODULE"
end
end
defmodule MyServer do
use GenServer
def start_link(state) do
GenServer.start_link(MyServer, state, name: via_tuple)
end
def init(state) do
{:ok, state}
end
defp get_name, do: {:n, :l, MyServer}
defp via_tuple, do: {:via, :gproc, get_name}
def hello(string) do
:gproc.send(get_name, string)
end
def get_state do
case :gproc.lookup_local_name(MyServer) do
:undefined -> :meck.passthrough
pid -> GenServer.call(pid, :get_state)
end
end
def handle_call(:get_state, from, state) do
{:reply, state, state}
end
def handle_call(msg, from, state) do
IO.inspect "Got #{inspect msg} in process #{inspect self()}, from: #{inspect from}"
{:reply, msg, state}
end
def handle_info(msg, state) do
IO.inspect "Got #{inspect msg} in process #{inspect self()}"
{:noreply, state}
end
end
defmodule MyServerTest do
use ExUnit.Case, async: true
setup_all do
:meck.expect(StubbedModule, :get_state, &MyServer.get_state/0)
end
setup do
{:ok, pid} = Task.Supervisor.start_link
{:ok, %{pid: pid}}
end
test "named genserver access local" do
{:ok, _pid} = MyServer.start_link(:local)
assert StubbedModule.get_state == :local
end
test "named genserver access from async_nolink", %{pid: sup} do
{:ok, _pid} = MyServer.start_link(:async_nolink)
Task.Supervisor.async_nolink(sup, fn ->
assert StubbedModule.get_state == :async_nolink
end)
|> Task.await
end
test "named_server not running" do
assert StubbedModule.get_state == "ACTUAL MODULE"
end
test "named_server not running from async_nolink", %{pid: sup} do
Task.Supervisor.async_nolink(sup, fn ->
assert StubbedModule.get_state == "ACTUAL MODULE"
end)
|> Task.await
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment