Paradox

Paradox

Blog Post: Some Elixir Testing Tricks

Testing is an important part of any modern piece of software. But writing tests can quickly become an exercise in frustration, with tons of repeated code, duplicate setup routines, and cumbersome assertions. ExUnit, Elixir’s testing framework, is ultimately just pure Elixir, and so we can extend it using more elixir features. Isolated setup units that can be mixed and matched, configuration via tags, and custom assertions are trivial to add to a test suite, and can save tons of developer headache

First Post!

dimitarvp

dimitarvp

Thanks, pretty useful. I already used part of these so I am definitely stealing using the others.

Most Liked

Paradox

Paradox

I’ll look into improving them in an Elixir PR this weekend!

Indeed. But since tags are handled by the compiler (they’re just attributes, you can register your own for anything via Module.register_attribute/3. This is how some tools like Absinthe register their documentation and such.

Interestingly, ExUnit also provides a register_attribute/2, which can be used to register attributes for use only in tests. They show up under context.registered, i.e.:

@fixture :foo
# registers as
context.registered.fixture == :foo

There’s also a sibling one for describe attributes, register_describe_attribute/2 and one for modules, register_module_attribute/2, which can be used as described.

I’ve used the TAP formatter in the past to check test names. You can also follow the red-green-red pattern of testing, where you make the tests deliberately fail on the first run, to check the setup. If the test is empty you’ll get a warning about it not being implemented, and if you just want to force a fail you can assert false.

linusdm

linusdm

Very well written and useful. Thx for sharing!

It prompted me to review the documentation of the ExUnit.Case module. I’ve never used tags before, but the examples you provide in the blogpost are very clear. I’d even argue that you could easily improve the existing docs on tags with an example from your post. I wouldn’t have guessed that the tags are passed into the setup callbacks, and take advantage of them (combined with the pattern matching superpowers) like you showed. Super handy indeed. It could as well have worked the other way: setup callbacks are run first, and the tag value is merged into the context last. That’s not clear from the current documentation on tags, afaik.

While reading up on the tag docs I also noticed that you can do:

@tag :admin

which is equivalent to:

@tag admin: true

This spares another four characters :slight_smile:

The last part on how to generate tests with the for-comprehension prompted another question: can you run the tests in a way that it prints out all the test names that are run, also if they pass? When you’re generating tests like that, it’s nice to see the generated test name at least once, to see if it will make sens if they fail. I know you should start with a failing test, but still… :slight_smile: Would be nice to have a formatter that prints more than just a green dot for every passing test. There is a CLI option to override the default formatter, but I didn’t find any bundled formatter that I could pass in.

sodapopcan

sodapopcan

I very much echo the “great article” sentiments and thank you for making me aware of TAP!

I have a somewhat similar helper as your assert_html for LiveView tests to narrow down text within a certain element which I find myself doing a fair bit often:

defmacro assert_within(lv, selector, text_or_regex) do
  quote do
    assert unquote(lv)
           |> element(unquote(selector))
           |> render() =~ unquote(text_or_regex)
  end
end

assert_within(lv, ".comments", "Product was definitely broken when it arrived, please send another.")

Last Post!

lud

lud

This is my current command to run the tests:

mix test --failed --max-failures 1 --seed $(odo -c _build/seed.txt) && \
mix test --stale  --max-failures 1 --seed $(odo -c _build/seed.txt) && \
odo _build/seed.txt

odo is a simple counter that reads or increments a number from a file.

So what is does is:

  • as long as I have a failing test, it will only run that test, thanks to the seed
  • when this test passes, it will now fail repeatedly on the next failing test
  • when all my previously failing tests pass, it will run all the stale tests. If one of them fails, the loop will start over.
  • if everything passes, we increment the seed to preserve a minimum of entropy like designed in ExUnit.

A simple shortcut for vscode:

  {
    "key": "ctrl+alt+u",
    "command": "workbench.action.terminal.sendSequence",
    "args": {
      "text": "mix test --failed --max-failures 1 --seed $(odo -c _build/seed.txt) && mix test --stale --max-failures 1 --seed $(odo -c _build/seed.txt) && odo _build/seed.txt\n"
    }
  },

Where Next?

Popular in Blog Posts Top

sashaafm
How to use the blogs section You can post links to your blog posts either in one of the Official Blog Posts threads (like this one), or, ...
296 25843 131
New
AstonJ
Elixir Blog Posts How to use this section You can post links to your blog posts either in one of the Official Blog Posts threads, or, vi...
New
AstonJ
I think <span class="hashtag-icon-placeholder"></span>liveview is going to be a big topic in the foreseeable future, so wondering whether...
New
paulanthonywilson
I had a bit of a mini-adventure following Sobelow’s advice on adding a CSP to a Phoenix App. If you want to follow along, or want to add ...
New
brainlid
You are storing some Phoenix LiveView state in the browser. You want to retrieve that saved state as early as possible to improve the use...
New
fredwu
Hi folks, I wrote a blog post the other day on how I built my MVP in 3 months whilst having a day job, using Elixir/Phoenix/LiveView. Th...
New
lawik
One of the Erlang ecosystem’s spiciest nerd snipes are hot code updates. Because it can do it. In ways that almost no other runtime can.
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New

We're in Beta

About us Mission Statement