Module: Hanko::TestHelper

Defined in:
lib/hanko/test_helper.rb

Overview

Test utilities for generating JWT tokens and stubbing Hanko endpoints.

Provides helpers that make it easy to test Hanko authentication without hitting a real Hanko API.

Examples:

Generate a test token and stub JWKS

token = Hanko::TestHelper.generate_test_token(sub: "user-123", exp: Time.now.to_i + 3600)
Hanko::TestHelper.stub_jwks(api_url: "https://example.hanko.io")

Defined Under Namespace

Classes: StubVerifier

Class Method Summary collapse

Class Method Details

.generate_test_token(sub:, exp:, **extra_claims) ⇒ String

Generates a signed JWT test token using an ephemeral RSA key.

Examples:

token = Hanko::TestHelper.generate_test_token(sub: "user-123", exp: Time.now.to_i + 3600)

Parameters:

  • sub (String)

    the subject claim (user ID)

  • exp (Integer)

    the expiration time as a Unix timestamp

  • extra_claims (Hash)

    additional claims to include in the payload

Returns:

  • (String)

    the encoded JWT token



44
45
46
47
# File 'lib/hanko/test_helper.rb', line 44

def generate_test_token(sub:, exp:, **extra_claims)
  payload = { 'sub' => sub, 'exp' => exp }.merge(extra_claims.transform_keys(&:to_s))
  JWT.encode(payload, test_key, 'RS256', kid: test_kid)
end

.stub_jwks(api_url:) ⇒ WebMock::RequestStub

Stubs the JWKS endpoint using WebMock so tokens from generate_test_token can be verified.

Examples:

Hanko::TestHelper.stub_jwks(api_url: "https://example.hanko.io")

Parameters:

  • api_url (String)

    the Hanko API base URL

Returns:

  • (WebMock::RequestStub)

    the WebMock stub



64
65
66
67
# File 'lib/hanko/test_helper.rb', line 64

def stub_jwks(api_url:)
  WebMock::API.stub_request(:get, "#{api_url}/.well-known/jwks.json")
              .to_return(status: 200, body: test_jwks_response)
end

.stub_session(sub:, exp:, **extra_claims) ⇒ StubVerifier

Creates a StubVerifier that returns a fixed session payload without cryptographic verification.

Examples:

verifier = Hanko::TestHelper.stub_session(sub: "user-123", exp: Time.now.to_i + 3600)
verifier.verify("any-token") #=> {"sub" => "user-123", "exp" => ...}

Parameters:

  • sub (String)

    the subject claim (user ID)

  • exp (Integer)

    the expiration time as a Unix timestamp

  • extra_claims (Hash)

    additional claims to include in the payload

Returns:

  • (StubVerifier)

    a verifier that returns the given payload



79
80
81
82
# File 'lib/hanko/test_helper.rb', line 79

def stub_session(sub:, exp:, **extra_claims)
  payload = { 'sub' => sub, 'exp' => exp }.merge(extra_claims.transform_keys(&:to_s))
  StubVerifier.new(payload)
end

.test_jwks_responseString

Returns a JSON string containing the test JWKS (public key set).

Returns:

  • (String)

    JSON-encoded JWKS response body



52
53
54
55
# File 'lib/hanko/test_helper.rb', line 52

def test_jwks_response
  jwk = JWT::JWK.new(test_key, kid: test_kid)
  { keys: [jwk.export] }.to_json
end