Testing Your App
What You'll Learn
Prerequisites
Step 1: Test Setup
require "spec"
require "../src/user_api"
# Test configuration
module TestConfig
def self.setup
# Use test database
ENV["DATABASE_URL"] = "sqlite3://./test.db"
ENV["AZU_ENV"] = "test"
end
end
# Helper module for creating test contexts
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 parse_response(context : HTTP::Server::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
# Setup before all tests
TestConfig.setup
Spec.before_each do
# Clean database before each test
User.delete_all if defined?(User)
endStep 2: Testing Endpoints
Step 3: Testing Request Validation
Step 4: Testing Models
Step 5: Testing WebSocket Channels
Step 6: Integration Tests
Step 7: Running Tests
Test Organization
Best Practices
Key Concepts Learned
Test Structure
Common Assertions
Next Steps
Last updated
Was this helpful?
