我有一个用于创建用户的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
我的端点返回3个字段:email,image_url和id。我目前无法通过此测试,因为我无法分辨新创建的资源的ID是什么。有没有更好的方法来测试这个?
答案 0 :(得分:2)
在这种情况下,我通常会跳过检查确切的值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)