...

/

Making Tests Repeatable—Continued

Making Tests Repeatable—Continued

Let’s continue writing tests for impure functions.

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:

Press + to interact
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. ...