问题描述
具有以下基本测试(使用ex_machina):
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]
使用"published_at" => "#{item.published_at}"
但仍然失败:
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 ?
推荐答案
item.published_at
是NaiveDateTime
结构.当将其转换为JSON时,编码器(此处可能为Poison
)会将其转换为ISO8601字符串表示形式.
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.
您的第一次尝试失败,因为您正在将NaiveDateTime
结构与String
进行比较.第二个失败,因为NaiveDateTime
的String.Chars
实现使用与ISO8601不同的表示形式.
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.
解决此问题的最简单方法是将published_at
手动转换为其ISO 8601表示形式:
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),
...
}
]
这篇关于凤凰/控制器中的测试日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!