Search⌘ K
AI Features

Tests Call the API as a User Would—Helper Functions

Discover how to test Elixir API boundaries by using helper functions that mimic user actions, such as starting a quiz, selecting questions, and submitting answers. Explore setting up the test environment with persistence and templates, ensuring reliable and clear test outputs.

Starting and taking a quiz

Now, we can move on to the helpers that will let us build, start, and take the quiz:

C++
defp start_quiz(fields) do
now = DateTime.utc_now()
ending = DateTime.add(now, 60)
Mastery.schedule_quiz(Math.quiz_fields(), fields, now, ending)
end
defp take_quiz(email) do
Mastery.take_quiz(Math.quiz.title, email)
end
  • start_quiz schedules the quiz to start immediately with more than enough time to take the quiz. We’ll achieve mastery far before the timer runs out.

  • take_quiz lets a user establish a session.

Answering a quiz

Now, we can move on to the helpers to answer a quiz:

C++
defp select_question(session) do
assert Mastery.select_question(session) == "1 + 2"
end
defp give_wrong_answer(session) do
Mastery.answer_question(
session,
"wrong", &MasteryPersistence.record_response/2
)
end
defp give_right_answer(session) do
Mastery.answer_question(
session,
"3", &MasteryPersistence.record_response/2
)
end

By now, these functions should be pretty familiar. We have a function to select a question and then a couple of functions to provide right and wrong answers. Notice that we provide the persistence function to use for saving the responses. That way, only the tests that use these functions will actually persist ...