Testing our Poll schema
While it's great that we have written some code that describes our Poll object in the database, it's no good if we can't actually validate that the code does what we need it to. A good way for us to test this, since we haven't hooked anything up to our controllers yet, is to run our tests in IEx instead!
We'll need to alias a few modules first, to make our lives a little easier when we're writing our code. We’ll start off with aliasing Vocial.Votes.Poll and Vocial.Repo. The first alias gives us access to our changeset and Poll struct, whereas the second gives us access to the Repo.insert() function, which we'll use to actually get the data into the database. Next, we need to create the actual changeset, since that tells Ecto how to actually get that insert statement into the database. We'll do this through the Poll.changeset() function, and pass it in a blank Poll struct as our starting point (remember our earlier conversation about how changesets are always modifications on top of some starting structure?). Finally, we'll pass the resulting finished changeset into the Repo.insert() function, and we'll see an insert SQL statement appear in our IEx window:
iex(1)> alias Vocial.Votes.Poll
Vocial.Votes.Poll
iex(2)> alias Vocial.Repo
Vocial.Repo
iex(3)> changeset = Poll.changeset(%Poll{}, %{title: "Sample Poll"})
#Ecto.Changeset<action: nil, changes: %{title: "Sample Poll"}, errors: [],
data: #Vocial.Votes.Poll<>, valid?: true>
iex(4)> Repo.insert(changeset)
[debug] QUERY OK db=51.9ms queue=0.1ms
INSERT INTO "polls" ("title","inserted_at","updated_at") VALUES ($1,$2,$3) RETURNING "id" ["Sample Poll", {{2017, 10, 5}, {20, 18, 8, 931657}}, {{2017, 10, 5}, {20, 18, 8, 933798}}]
{:ok,
%Vocial.Votes.Poll{__meta__: #Ecto.Schema.Metadata<:loaded, "polls">, id: 1,
inserted_at: ~N[2017-10-05 20:18:08.931657], title: "Sample Poll",
updated_at: ~N[2017-10-05 20:18:08.933798]}}
Sure enough, if we take a look at the database, we'll see that the data from our insert statement was successfully inserted into the database:
This is a pretty great bit of progress! Let's continue our momentum by creating our (admittedly trickier) option schema!