Documentation for LLMs on building APIs with the Apia framework
Apia provides built-in support for testing endpoints with mock requests.
Use Endpoint.test to execute an endpoint with a mock request:
# Test an endpoint directly
result = MyAPI::Endpoints::Users::InfoEndpoint.test do |req|
req.identity = mock_user
req.arguments[:user_id] = "abc-123"
end
Use API.test_endpoint to test through the full API stack including authentication:
result = MyAPI::Base.test_endpoint(
MyAPI::Endpoints::Users::InfoEndpoint,
controller: MyAPI::Controllers::UsersController
)
The MockRequest class provides a test double for HTTP requests:
RSpec.describe MyAPI::Endpoints::Users::InfoEndpoint do
it "returns user details" do
user = create(:user)
response = described_class.test do |req|
req.identity = user
end
expect(response.status).to eq(200)
expect(response.hash[:user][:name]).to eq(user.name)
end
end
it "raises an error when user not found" do
expect {
described_class.test do |req|
req.identity = create(:user)
req.arguments[:user_id] = "nonexistent"
end
}.to raise_error(Apia::ErrorExceptionError) do |error|
expect(error.error_class.definition.code).to eq(:user_not_found)
end
end
Since Apia runs as Rack middleware, you can also test it with standard Rack test helpers:
RSpec.describe "Users API", type: :request do
it "returns user info" do
user = create(:user)
token = create(:api_token, user: user)
get "/api/v1/user",
headers: { "Authorization" => "Bearer #{token.value}" }
expect(response).to have_http_status(200)
json = JSON.parse(response.body)
expect(json["user"]["name"]).to eq(user.name)
end
end