62 lines
2.1 KiB
Ruby
62 lines
2.1 KiB
Ruby
require "rails_helper"
|
|
|
|
RSpec.describe "Sessions API", type: :request do
|
|
let!(:user) { User.create!(nickname: "Columbus", password: "securepassword") }
|
|
let(:token) { JwtService.encode(user_id: user.id) }
|
|
|
|
describe "POST /api/login" do
|
|
it "logs in with valid credentials and returns 200 OK with token" do
|
|
post "/api/login", params: { nickname: "Columbus", password: "securepassword" }, as: :json
|
|
|
|
expect(response).to have_http_status(:ok)
|
|
json = JSON.parse(response.body)
|
|
expect(json["token"]).to be_present
|
|
expect(json["user"]["id"]).to eq(user.id)
|
|
expect(json["user"]["nickname"]).to eq("Columbus")
|
|
end
|
|
|
|
it "returns 401 Unauthorized with invalid credentials" do
|
|
post "/api/login", params: { nickname: "Columbus", password: "wrongpassword" }, as: :json
|
|
|
|
expect(response).to have_http_status(:unauthorized)
|
|
json = JSON.parse(response.body)
|
|
expect(json["error"]).to eq("Invalid nickname or password")
|
|
end
|
|
end
|
|
|
|
describe "DELETE /api/logout" do
|
|
it "signs out successfully when bearer token is supplied" do
|
|
delete "/api/logout", headers: { "Authorization" => "Bearer #{token}" }
|
|
|
|
expect(response).to have_http_status(:ok)
|
|
json = JSON.parse(response.body)
|
|
expect(json["message"]).to eq("Signed out successfully")
|
|
end
|
|
|
|
it "returns 401 Unauthorized when unauthenticated" do
|
|
delete "/api/logout"
|
|
|
|
expect(response).to have_http_status(:unauthorized)
|
|
end
|
|
end
|
|
|
|
describe "GET /api/me" do
|
|
it "returns user profile with Bearer authorization header" do
|
|
get "/api/me", headers: { "Authorization" => "Bearer #{token}" }
|
|
|
|
expect(response).to have_http_status(:ok)
|
|
json = JSON.parse(response.body)
|
|
expect(json["user"]["id"]).to eq(user.id)
|
|
expect(json["user"]["nickname"]).to eq("Columbus")
|
|
end
|
|
|
|
it "returns 401 Unauthorized when Authorization header is missing" do
|
|
get "/api/me"
|
|
|
|
expect(response).to have_http_status(:unauthorized)
|
|
json = JSON.parse(response.body)
|
|
expect(json["error"]).to eq("Unauthorized")
|
|
end
|
|
end
|
|
end
|