Fl4m3Ph03n1x

Fl4m3Ph03n1x

How to test side effects on other processes?

Background

I have a module that makes a async request to another service. This async request is made via Task.start and I literally don’t care if the request fails or not, I only want to make it.

My objective here, is to test whether or not I am making the request with the correct parameters.

Code

The function send takes in a params string and an options keyword list. This keywords list allows me to inject the function that actually makes the HTTP GET request opts[:request_fn].().

def send(params, opts \\ []) do

    Task.start(fn ->
      params
      |> build_url
      |> opts[:request_fn].()
    end)
  end

 
  defp build_url(params) do
      "www.google.com/search?" <> params
  end

Problem

The problem here is that there is no way for me to test whether or not the newly created process is doing what it is told. it may be called opts[:request_fn].() with the wrong parameters, or it may not be calling it at all.

Even if :request_fn is set to fail:

request_fn = fn url ->
 IO.puts("url #{url}")
 assert 1 ==2
 throw(:nok)
end

The tests still complete successfully because the error is in another process and not in the one running the test.

Possible solutions

A possible solution came to me from reading a blog on Elixir testing. It pretty much boils down to creating a GenServer with a publish and subscribe setting, and then making the newly created task send a message to the server’s mailbox. I would then have the test process subscribe to said mailbox and verify that a given message was received.

This has a few problems:

  1. I cannot run the tests asynchrousnly
  2. I find it overkill to create a whole pub/sub server and to add that logic to my application only so I can test it

And all this because elixir provides no easy way to just spy on a function and check if it was invoked or not.

Questions

Without spies, how do you test for side effects on other processes that don’t communicate with you?

Marked As Solved

van-mronov

van-mronov

Even if it looks like you test your implementation of request_fn you can do something like this in your test:

pid = self()

request_fn = fn url ->
 IO.puts("url #{url}")
 send(pid, :nok)
end

send(params, request_fn: request_fn)
assert_receive :nok

Also Liked

peerreynders

peerreynders

That tactic is incredibly useful in all sorts of situations. Unfortunately there isn’t some catchy name associated with it (“Informant function”?).

That is likely due to the fact that there is a range of potential techniques around assert_receive/3, assert_received/2, refute_receive/3 and refute_receive/2 that

  • start simply with the test process injecting it’s pid into the “process under test” to become the recipient of all messages,
  • to the test process launching any number of faux processes (or GenServers) to meet the collaboration needs of the “process under test”.
van-mronov

van-mronov

Yeah, I use this pattern often, especially in tests. So, informative name could help to address these techniques. Maybe “Callback notifiers”, I’m not sure.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement