Testing Your App

This tutorial teaches you how to write comprehensive tests for your Azu application, including endpoints, models, and WebSocket channels.

What You'll Learn

By the end of this tutorial, you'll be able to:

  • Set up a testing environment

  • Write unit tests for endpoints

  • Test request validation

  • Test database models

  • Test WebSocket channels

Prerequisites

  • Completed previous tutorials

  • Basic understanding of testing concepts

Step 1: Test Setup

Create spec/spec_helper.cr:

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)
end

Step 2: Testing Endpoints

Create spec/endpoints/create_user_endpoint_spec.cr:

Create spec/endpoints/show_user_endpoint_spec.cr:

Step 3: Testing Request Validation

Create spec/requests/create_user_request_spec.cr:

Step 4: Testing Models

Create spec/models/user_spec.cr:

Step 5: Testing WebSocket Channels

Create spec/channels/notification_channel_spec.cr:

Step 6: Integration Tests

Create spec/integration/api_spec.cr:

Step 7: Running Tests

Run all tests:

Run specific test file:

Run with verbose output:

Run focused tests:

Test Organization

Best Practices

  1. Test one thing per test - Each test should verify one specific behavior

  2. Use descriptive names - Test names should describe the expected behavior

  3. Clean up after tests - Reset database state between tests

  4. Mock external services - Don't call real external APIs in tests

  5. Test edge cases - Include tests for error conditions and boundary values

Key Concepts Learned

Test Structure

Common Assertions

Next Steps

You've learned to test your Azu application. Continue with:


Your tests are ready! You now have comprehensive test coverage for your application.

Last updated

Was this helpful?