Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Testing Phoenix API:如果我没有';我不知道新资源的ID?_Testing_Elixir_Phoenix Framework - Fatal编程技术网

Testing Phoenix API:如果我没有';我不知道新资源的ID?

Testing Phoenix API:如果我没有';我不知道新资源的ID?,testing,elixir,phoenix-framework,Testing,Elixir,Phoenix Framework,我有一个用于创建用户的POST/api/v1/users端点。这是我的失败测试: test "success" do user_params = %{ user: %{ email: "eric@spaghetti.com", image_url: "https://www.google.com/images/spaghetti", } } conn = build_conn(:post, "/api/v1/users", user_para

我有一个用于创建用户的POST/api/v1/users端点。这是我的失败测试:

test "success" do
  user_params = %{
    user: %{
      email: "eric@spaghetti.com",
      image_url: "https://www.google.com/images/spaghetti",
    }
  }

  conn = build_conn(:post, "/api/v1/users", user_params)
  response = Router.call(conn, @opts)
  assert response.status == 201
  assert Repo.get_by(User, %{email: user_params.user.email})
  assert response.resp_body == %{
    id: "how would I know this??", #<---------this would fail since I have no way of knowing what this value would be
    email: user.email,
    image_url: user.image_url,
  } |> Poison.encode!
end
测试“成功”吗
用户参数=%{
用户:%{
电子邮件:“eric@spaghetti.com",
图像\u url:“https://www.google.com/images/spaghetti",
}
}
conn=构建连接(:post,“/api/v1/users”,用户参数)
响应=路由器呼叫(conn,@opts)
assert response.status==201
断言Repo.get_by(用户,%{email:User_params.User.email})
assert response.resp_body==%{
id:“我怎么知道这个?”,#毒物.编码!
结束

我的端点返回3个字段:email、image\u url和id。我目前无法通过此测试,因为我无法确定新创建的资源的id是什么。是否有更好的方法来测试此项?

在这种情况下,我通常不检查确切的值
id
,而只检查它是否存在:

%{email: email, image_url: image_url} = user

assert %{
  "id" => _,
  "email" => ^email,
  "image_url" => ^image_url,
} = Poison.decode!(response.resp_body)
您还可以断言
id
是一个整数:

assert %{
  "id" => id,
  "email" => ^email,
  "image_url" => ^image_url,
} = Poison.decode!(response.resp_body)
assert is_integer(id)

我不熟悉phoenix和ecto,但是没有这样的功能来返回最后插入的行id吗?我打赌有。这不是一件事吗?对于新登录的客户端来说,知道它的id以便它可以使用它来发出未来的请求不是很有用的信息吗?看起来不允许使用这种语法吗?
无法调用远程函数用户.email/0内部匹配
Oops,对不起,我忘记了。让我想想另一种方法。我以前在LHS上对常量字符串使用这种语法,这很有效。如果您可以在前面的变量中存储
email
image\u url
,您可以使用pin操作符:
assert%{“email”=>^email,“image\u url”=>^image\u url}=…