Module: Machina::TestHelpers

Defined in:
lib/machina/test_helpers.rb

Overview

Test helpers for applications integrating with the machina-auth gem.

Include this module in your test framework to get convenience methods for setting up authenticated contexts in controller, request, and integration tests.

# RSpec
RSpec.configure do |config|
  config.include Machina::TestHelpers
end

# Minitest
class ActiveSupport::TestCase
  include Machina::TestHelpers
end

Instance Method Summary collapse

Instance Method Details

#sign_in_as_machina(tenant_ref = nil, user: {}, organization: {}, workspace: {}, session: {}, permissions: nil) ⇒ Machina::Authorized

Sets Machina::Current.authorized to a fully-populated Authorized instance built from the provided overrides merged onto realistic defaults. Returns the Authorized object.

The first argument is tenant_ref — the workspace ID that scopes all multi-tenant queries. This is the value you’ll use most often, so it’s positional to keep tests concise.

rubocop:disable Metrics/AbcSize, Metrics/ParameterLists

Examples:

Minimal — uses all defaults

With a specific tenant

("ws-uuid-1")

With tenant and permissions

("ws-uuid-1", permissions: ["reports.view"])

Full control

(
  "ws-uuid-1",
  user: { email: "alice@example.com" },
  permissions: ["reports.view", "reports.create"]
)

Parameters:

  • tenant_ref (String) (defaults to: nil)

    workspace ID used as tenant_ref (defaults to a stable test UUID)

  • user (Hash) (defaults to: {})

    overrides for user attributes (id, email, name, avatar_url)

  • organization (Hash) (defaults to: {})

    overrides for organization attributes (id, name, personal, role)

  • workspace (Hash) (defaults to: {})

    additional workspace overrides beyond id (name)

  • session (Hash) (defaults to: {})

    overrides for session attributes (id, type, expires_at)

  • permissions (Array<String>) (defaults to: nil)

    granted permission keys

Returns:



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/machina/test_helpers.rb', line 55

def (
  tenant_ref = nil,
  user: {},
  organization: {},
  workspace: {},
  session: {},
  permissions: nil
)
  data = default_session_data

  data['user'].merge!(stringify(user))
  data['session'].merge!(stringify(session))
  data['workspace'].merge!(stringify(workspace))
  data['organization'].merge!(stringify(organization))
  data['workspace']['id'] = tenant_ref.to_s if tenant_ref
  data['permissions'] = permissions.map(&:to_s) if permissions

  authorized = Machina::Authorized.new(data)
  Machina::Current.authorized = authorized
  authorized
end

#sign_out_machinaObject

Clears the current authenticated context.



79
80
81
# File 'lib/machina/test_helpers.rb', line 79

def sign_out_machina
  Machina::Current.reset
end