Shoring up our tests

Next, we can move on to actually writing our tests. We'll want to test two things, specifically:

  1. When we have multiple polls, we want to return them in the order of most-recently created to least-recently created.
  2. When we are including pagination params (page and per_page), we should get the correct results (also respecting ordering).

We'll start with a test to cover the first scenario, since that should be pretty simple to write:

test "list_most_recent_polls/2 returns polls ordered by the most recent first", %{user: user} do
poll = poll_fixture(%{user_id: user.id})
poll2 = poll_fixture(%{user_id: user.id})
poll3 = poll_fixture(%{user_id: user.id})
assert Votes.list_most_recent_polls() == [poll3, poll2, poll]
end

What we're doing here is creating three polls specifically, and then verifying that when we call our new list_most_recent_polls function with no arguments, that we just get back the default page size and first page, and that the results are ordered correctly. The end result should be poll3, poll2, and then poll. Run the test, verify the result, and then we'll move on to our next test, which should be a little bit more complicated:

test "list_most_recent_polls/2 returns polls ordered and paged correctly", %{user: user} do
_poll = poll_fixture(%{user_id: user.id})
_poll2 = poll_fixture(%{user_id: user.id})
poll3 = poll_fixture(%{user_id: user.id})
_poll4 = poll_fixture(%{user_id: user.id})
assert Votes.list_most_recent_polls(1, 1) == [poll3]
end

This is a little bit stranger. We're creating four polls instead of three, and we're prefixing some of the variables with an underscore! The reason for the underscores is that we don't actually need the variable, but it's still worth us keeping track of which poll is which.

An underscore prefixing any variable in Elixir means that the variable will not be used later.

We also create four polls instead of three because if we left the number of polls at three, we wouldn't actually be able to tell that our polls were ordered correctly (since poll2 would be the first offset poll after the first page in either order). This allows us to verify all of the behavior at the same time without making a bunch of extra weird assumptions!

Run the tests for this file, verify that they are green and passing, and we can move on to hooking this up to the controller and templates!:

$ mix test test/vocial/votes/votes_test.exs
.............

Finished in 4.2 seconds
13 tests, 0 failures

Randomized with seed 906033
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset