Re: [elixir-core:10901] [Proposal] Scoped function definitions in Exunit's describe

54 views
Skip to first unread message

José Valim

unread,
May 24, 2022, 3:47:45 PM5/24/22
to elixir-lang-core
A describe is still a single module, so there is no way to achieve what you desire using describe. You should rather use separate modules (and you can share the setups between them).

On Tue, May 24, 2022 at 7:34 PM Jakub Gonet <jakub....@gmail.com> wrote:
When writing tests I frequently write small helpers which are used to shorten the tests.
Examples:
- when testing mixins I added a module in describe with use Mixin, some_configuration and created helper that called its injected function
- when testing Phoenix controller I created function that requests a tested path, given conn as an argument

I noticed that describe blocks don't create module scope so while it looks like those functions are scoped to given describe, they're shared between all tests in the file instead.

If implemented, this feature could improve the locality of helpers (so you don't have to scroll all the way down to see helper's implementation) and allowed helpers to share the names.

Example:
defmodule DescribeFns do
  def foo, do: :foo

  def bar, do: 5
end

defmodule DescribeFnsTest do
  use ExUnit.Case

  describe "foo/0" do
    test "foo test" do
      assert "foo" == stringify(DescribeFns.foo())
    end

    defp stringify(atom) do
      Atom.to_string(atom)
    end
  end

  describe "bar/0" do
    test "bar test" do
      assert "5" == stringify(DescribeFns.bar())
    end

    defp stringify(number) do
      Integer.to_string(number)
    end
  end
end


Compiles with warning:

$ mix test
warning: this clause for stringify/1 cannot match because a previous clause at line 15 always matches
  test/describe_fns_test.exs:25

And obviously, bar/0 test fails.

--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/46d08242-15e1-4a9c-8271-3f60d8ad8ee5n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages