官术网_书友最值得收藏!

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!

主站蜘蛛池模板: 平乐县| 仙居县| 泽州县| 九江县| 盖州市| 台湾省| 久治县| 新蔡县| 新源县| 辽宁省| 吉隆县| 泗洪县| 威远县| 定襄县| 临朐县| 仲巴县| 云林县| 芜湖市| 夏津县| 夹江县| 岐山县| 伊宁市| 黔西| 双辽市| 海城市| 苍溪县| 山东| 贵港市| 连山| 平谷区| 乌拉特后旗| 平和县| 涟源市| 资源县| 灵璧县| 宜春市| 武夷山市| 巢湖市| 唐海县| 阿拉善左旗| 大同县|