Search⌘ K
AI Features

Making Tests Repeatable—Continued

Explore methods to make tests repeatable in Elixir by handling randomness in your code. Understand how to use streams to generate random numbers and ensure your tests can consistently verify expected outcomes despite inherent randomness.

Random numbers

We’ve successfully dodged the idea of random numbers, but it’s time to pay the piper. We have to solve for the fact that we don’t have repeatable results when we generate a question using random numbers, so we’ll have to improvise.

We can use streams to generate many random numbers, and then narrow that value to the one we need. We’ll be entering this now in /test/question_test.exs:

C++
test "a random choice is made from list generators" do
generators = addition_generators(Enum.to_list(1..9), [0])
assert eventually_match(generators, 1)
assert eventually_match(generators, 9)
end
def eventually_match(generators, answer) do
Stream.repeatedly(fn ->
build_question(generators: generators).substitutions
end)
|> Enum.find(fn substitution ->
Keyword.fetch!(substitution, :left) == answer end)
end
end

Let’s try this out by entering the following commands:

Note: If you restart the iex terminal, you’ll have to enter the setup commands mentioned above again. Otherwise, ...