Use underscore (_) in ExUnit tests
Asked Answered
C

1

7

I have a method in my elixir app, let's say Some.Module.func/1, that returns a tuple of two numbers. I'm writing tests in ExUnit and only need to test the first element in tuple and don't really care about the second one.

So far, I've tried doing this:

test "some method" do
    assert Some.Module.func(45) == {54, _}
end

But I just get this error when running the test:

Compiled lib/some.ex
Generated some app
** (CompileError) test/some_test.exs:7: unbound variable _
    (stdlib) lists.erl:1353: :lists.mapfoldl/3
    (stdlib) lists.erl:1354: :lists.mapfoldl/3

Why isn't this working, and how can I ignore unneeded results in my tests?

Culprit answered 24/10, 2015 at 16:33 Comment(0)
K
13

You can't match like that with assert when using ==. You can do the following with =:

test "some method" do
  assert {54, _} = Some.Module.func(45)
end

Note that the order has been reversed as the _ can only appear on the left hand side of the = operator, otherwise you will receive a CompileError which is what you are getting:

iex(3)> 3 = _
** (CompileError) iex:3: unbound variable _
    (elixir) src/elixir_translator.erl:17: :elixir_translator.translate/2

You can also do:

test "some method" do
  {result, _} = Some.Module.func(45)
  assert result == 54
end

Which may work in situations where you want to perform multiple assertions on the result.

Kent answered 24/10, 2015 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.