Test Endpoints

This guide shows you how to write tests for your Azu endpoints.

Basic Test Setup

Create a spec helper:

# spec/spec_helper.cr
require "spec"
require "../src/app"

module TestHelpers
  def create_context(
    method : String = "GET",
    path : String = "/",
    body : String? = nil,
    headers : HTTP::Headers = HTTP::Headers.new
  ) : HTTP::Server::Context
    io = IO::Memory.new
    request = HTTP::Request.new(method, path, headers, body)
    response = HTTP::Server::Response.new(io)
    HTTP::Server::Context.new(request, response)
  end

  def json_headers : HTTP::Headers
    headers = HTTP::Headers.new
    headers["Content-Type"] = "application/json"
    headers
  end

  def with_auth(headers : HTTP::Headers, token : String) : HTTP::Headers
    headers["Authorization"] = "Bearer #{token}"
    headers
  end

  def parse_json_response(context) : JSON::Any
    context.response.close
    body = context.response.@io.as(IO::Memory).to_s
    JSON.parse(body.split("\r\n\r\n").last)
  end
end

Testing GET Endpoints

Testing POST Endpoints

Testing PUT/PATCH Endpoints

Testing DELETE Endpoints

Testing with Authentication

Integration Tests

Test the full request/response cycle:

Testing Response Format

Running Tests

See Also

Last updated

Was this helpful?