phoenix / testing dates in controllers

守給你的承諾、 提交于 2019-12-11 18:55:57

问题


Having the following basic test (using ex_machina) :

# factory
def item_factory do
  %Api.Content.Item{
    title: "Some title",
    content: "Some content",
    published_at: NaiveDateTime.utc_now
  }
end

# test
test "lists all items", %{conn: conn} do
  item = insert(:item)
  conn = get conn, item_path(conn, :index)
  assert json_response(conn, 200)["data"] == [
    %{
      "content" => item.content,
      "published_at" => item.published_at,
      "title" => item.title,
      "id" => item.id
    }
  ]
end

Am getting an error on the date :

left: ... "published_at" => "2010-04-17T14:00:00.000000"
right: ... "published_at" => ~N[2010-04-17 14:00:00.000000]

Tried a simple string assertion with "published_at" => "#{item.published_at}"

But still failing with :

left: ..."published_at" => "2010-04-17T14:00:00.000000"
right: ..."published_at" => "2010-04-17 14:00:00.000000"

What would be the correct way to assert such case — how to correctly "cast" a date ?


回答1:


item.published_at is a NaiveDateTime struct. When it's converted to JSON, the encoder (likely Poison here) converts it to its ISO8601 string representation.

Your first attempt fails because you're comparing a NaiveDateTime struct to a String. The second one fails because the String.Chars implementation of NaiveDateTime uses a different representation than ISO8601.

The easiest way to fix this is to manually convert published_at to its ISO 8601 representation:

assert json_response(conn, 200)["data"] == [
  %{
    ...
    "published_at" => NaiveDateTime.to_iso8601(item.published_at),
    ...
  }
]


来源:https://stackoverflow.com/questions/52243868/phoenix-testing-dates-in-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!