4

I'm using ExUnit for testing my Elixir app, which is a card game.

I find that with every test I write, I start by creating a fresh deck of cards.

test "Do This Crazy Thing do
  deck = Deck.create()
  [...]
end

test "Do This Other Crazy Unrelated Thing" do
  deck = Deck.create()
   [...]
end

Is there a way to factor this out so that a new deck can just be created before every test case? I know there's something close to this with setup do [...] end, but I don't think that's the solution for me.

Do I need a different test framework? Do I need to use setup in some way I haven't thought of yet?

-Augie

2 Answers 2

9

You can use def setup with the meta has just for this.

Example:

defmodule DeckTest do
  use ExUnit.Case

  setup do
    {:ok, cards: [:ace, :king, :queen] }
  end

  test "the truth", meta do
    assert meta[:cards] == [:ace, :king, :queen]
  end
end

Here's some more info

Sign up to request clarification or add additional context in comments.

3 Comments

It looks like it works as you suggest, but it's not worth it in the end for me because it's possibly even more typing and repetition than it started with for my small needs. But, hey, I have that in the tool kit now for when I'll really need it. Thanks!
The link you posted is broken.
@nietaki which of the following links do you think is preferable: elixir-lang.org/docs/stable/ex_unit/… or elixir-lang.org/getting-started/mix-otp/…
1

Another option that could work depending on your needs:

defmodule DeckTest do
  use ExUnit.Case

  defp cards, do: [:ace, :king, :queen]

  test "the truth" do
    assert cards == [:ace, :king, :queen]
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.