访问列表中的嵌套元素,并在长生不老药中绘制地图



我是长生不老药的新手,在访问测试中的嵌套元素时遇到了一些问题。我正在测试控制器,到目前为止得到了以下响应:

.[%{"attributes" => %{"first_name" => "Timmy 96", "last_name" => 
"Assistant"},
"id" => "bca58c53-7c6e-4281-9bc8-0c4616a30051",
"relationships" => %{"avatar" => %{"data" => %{"id" => "011300fd-ca98-42b4-
9561-f1cdc93d2d25",
"type" => "pictures"}}}, "type" => "users"}]

我正在使用 JSON API 格式进行响应,并使用用户数据获取属性:

user_attr = Enum.filter(includes, fn(item)->
item["relationships"]["avatar"] != nil
end)
IO.inspect user_attr
case Enum.fetch(user_attr ,0) do
{:ok, value} ->
assert value["attributes"]["first_name"] == user.first_name
assert value["attributes"]["last_name"] == user.last_name
{_} ->
assert false
end

我想缩短这部分,不想使用案例,但不知道如何在不使用案例中的价值部分的情况下获取user_attr的值。

我还想断言关系的 id -> 头像 -> 数据 -> id 与我之前插入的 id,但不知道如何访问此值。id是我之前插入的图片的一部分,所以我想

assert XXX == picture.id

但是如何获得XXX?

希望有人能帮助我。去年只有Java和C#,从来没有Ruby,现在我不知何故进入了灵丹妙药:/

谢谢。

您可以使用get_in/2 来执行此操作。

iex()> list
[%{"attributes" => %{"first_name" => "Timmy 96", "last_name" => 
"Assistant"},
"id" => "bca58c53-7c6e-4281-9bc8-0c4616a30051",
"relationships" => %{"avatar" => %{"data" => %{"id" => "011300fd-ca98-
42b4-n9561-f1cdc93d2d25",
"type" => "pictures"}}}, "type" => "users"}]
iex()> [map] = list
[%{"attributes" => %{"first_name" => "Timmy 96", "last_name" => 
"Assistant"},
"id" => "bca58c53-7c6e-4281-9bc8-0c4616a30051",
"relationships" => %{"avatar" => %{"data" => %{"id" => "011300fd-ca98-
42b4-n9561-f1cdc93d2d25",
"type" => "pictures"}}}, "type" => "users"}]

iex()> get_in map, ["attributes", "first_name"]
"Timmy 96"
iex()> get_in map, ["attributes", "last_name"]
"Assistant"
iex()> get_in map, ["relationships", "avatar", "data", "id"]
"011300fd-ca98-42b4-n9561-f1cdc93d2d25"

您应该尝试更多地使用模式匹配。

# fixture data.
user = %{first_name: "Timmy 96", last_name: "Assistant"}
picture = %{id: "011300fd-ca98-42b4-n9561-f1cdc93d2d25"}
value = %{
"attributes" => %{"first_name" => "Timmy 96", "last_name" => "Assistant"},
"id" => "bca58c53-7c6e-4281-9bc8-0c4616a30051",
"relationships" => %{
"avatar" => %{
"data" => %{
"id" => "011300fd-ca98-42b4-n9561-f1cdc93d2d25",
"type" => "pictures",
},
},
},
"type" => "users",
}
assert %{"attributes" => attributes} = value
# ensure the expected value match with actual value and than bind the attributes variable with actual attributes map.
assert %{"first_name" => user.first_name, "last_name" => user.last_name} == attributes
assert %{"relationships" => %{"avatar" => %{ "data" => avatar_data}}} = value
assert %{"id" => picture.id, "type" => "pictures"} == avatar_data

Elixir最强大的功能之一是通过=运算符(match operator(进行模式匹配。

上面的例子表明,我们可以使用匹配运算符来断言期望值的数据结构与实际值匹配。

详细了解测试和模式匹配: https://semaphoreci.com/community/tutorials/introduction-to-testing-elixir-applications-with-exunit

最新更新