Hi everyone!
I’m trying to follow the tutorial from thoughtbot here to create my first phoenix json api endpoint. The code for the test is following:
# Create this test in test/controllers/todo_controller_test.exs
defmodule Todos.TodoControllerTest do
use Todos.ConnCase
test "#index renders a list of todos" do
conn = build_conn()
todo = insert(:todo)
conn = get conn, todo_path(conn, :index)
assert json_response(conn, 200) == %{
"todos" => [%{
"title" => todo.title,
"description" => todo.description,
"inserted_at" => Ecto.DateTime.to_iso8601(todo.inserted_at),
"updated_at" => Ecto.DateTime.to_iso8601(todo.updated_at)
}]
}
end
end
When I run the test I get the following error:
** (FunctionClauseError) no function clause matching in Ecto.DateTime.to_iso8601/1
stacktrace:
(ecto) lib/ecto/date_time.ex:584: Ecto.DateTime.to_iso8601(~N[2017-03-23 19:55:47.300335])
test/controllers/todo_controller_test.exs:14: (test)
I’ve completed the tutorial up to the point where this should be passing. If I change the test so that I’m not attempting to format the date I get the following:
Assertion with == failed
code: json_response(conn, 200) == %{"todos" => [%{"title" => todo.title(), "description" => todo.description(), "inserted_at" => "Frank", "updated_at" => "Frank"}]}
lhs: %{"todos" => [%{"description" => "List of steps I need to complete", "title" => "Something I need to do", "inserted_at" => "2017-03-23T19:56:39.484442", "updated_at" => "2017-03-23T19:56:39.497129"}]}
rhs: %{"todos" => [%{"description" => "List of steps I need to complete", "title" => "Something I need to do", "inserted_at" => "Frank", "updated_at" => "Frank"}]}
stacktrace:
test/controllers/todo_controller_test.exs:10: (test)
Which seems to make sense. The problem is with Ecto.DateTime.to_iso
and it’s no matching clause. The ecto code is this:
def to_iso8601(%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec, usec: usec}) do
str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> "T" <>
zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2)
if is_nil(usec) or usec == 0 do
str
else
str <> "." <> zero_pad(usec, 6)
end
end
So possibly the ~N[2017-03-23 19:57:48.500354]
is not matching with the
%Ecto.DateTime{year: year, month: month, day: day,
hour: hour, min: min, sec: sec, usec: usec}
in the ecto code? It is probably something small that I’m unaware of but I’ve very new to elixir and phoenix and would appreciate any advice on how to resolve this. Thanks so much for your time!