Making Tests Repeatable—Continued
Let’s continue writing tests for impure functions.
We'll cover the following...
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" dogenerators = addition_generators(Enum.to_list(1..9), [0])assert eventually_match(generators, 1)assert eventually_match(generators, 9)enddef eventually_match(generators, answer) doStream.repeatedly(fn ->build_question(generators: generators).substitutionsend)|> Enum.find(fn substitution ->Keyword.fetch!(substitution, :left) == answer end)endend
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. ...