ユーザーにサインインするエンドポイントがあります。私は統合テストとコントローラテストの両方を書いたが、コントローラテストでテストされたエッジケースが多いことを除けば(例:ユーザーが間違った電子メールでログインしようとしている)、非常によく似ている。テストの内容は実際には異なるようには見えないので、誰かがどのように違うべきかを明かすことができれば素晴らしいだろう。フェニックス:API統合テストとコントローラテスト
統合テスト:
defmodule SigningInUserTest do
use ParrotApi.ConnCase
alias ParrotApi.Router
@opts Router.init([])
describe "POST api/v1/sessions" do
test "success" do
email = "[email protected]"
password = "ilovemodals"
user = insert(:user,
email: email,
password_hash: Comeonin.Bcrypt.hashpwsalt(password))
user_params = %{
user: %{
email: user.email,
password: password,
}
}
conn = build_conn(:post, "/api/v1/sessions", user_params)
response = Router.call(conn, @opts)
assert response.status == 201
end
test "failure" do
email = "[email protected]"
password = "ilovemodalszzz"
user = insert(:user,
email: email,
password_hash: Comeonin.Bcrypt.hashpwsalt(password))
user_params = %{
user: %{
email: user.email,
password: "bad_password",
}
}
conn = build_conn(:post, "/api/v1/sessions", user_params)
response = Router.call(conn, @opts)
assert response.status == 401
end
end
コントローラーのテスト:
defmodule ParrotApi.SessionControllerTest do
use ParrotApi.ConnCase
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
describe "#create" do
test "returns the user when the email and password match", %{conn: conn} do
email = "[email protected]"
password = "ilovemodals"
user = insert(:user,
email: email,
password_hash: Comeonin.Bcrypt.hashpwsalt(password))
rsvp = insert(:rsvp, user: user)
user_params = %{
user: %{
email: email,
password: password,
}
}
conn = conn
|> post(session_path(conn, :create), user_params)
assert json_response(conn, 201)["data"] == %{
"id" => user.id,
"email" => user.email,
"name" => user.name,
"interests" => user.interests,
"location" => user.location,
"image_url" => user.image_url,
"is_admin" => user.is_admin,
"rsvps" => [rsvp.meetup_id],
}
end
test "returns an error when the email and password don't match", %{conn: conn} do
email = "[email protected]"
password = "ilovemodals"
insert(:user,
email: email,
password_hash: Comeonin.Bcrypt.hashpwsalt(password))
user_params = %{
user: %{
email: email,
password: "bad_password",
}
}
conn = conn
|> post(session_path(conn, :create), user_params)
assert json_response(conn, 401) == %{
"message" => "The email and password you entered did not match our records. Please try again."
}
end
test "returns an error when the user doesn't exist", %{conn: conn} do
user_params = %{
user: %{
email: "[email protected]",
password: "bad_password",
}
}
conn = conn
|> post(session_path(conn, :create), user_params)
assert json_response(conn, 401) == %{
"message" => "The email and password you entered did not match our records. Please try again."
}
end
end
end