Module: StandardId::Testing::RequestHelpers

Defined in:
lib/standard_id/testing/request_helpers.rb

Overview

Integration test helpers for signing in accounts and making authenticated requests.

Usage in rails_helper.rb:

require "standard_id/testing"

RSpec.configure do |config|
  config.include StandardId::Testing::RequestHelpers, type: :request
end

Instance Method Summary collapse

Instance Method Details

#bearer_auth_header(token) ⇒ Hash

Returns an Authorization header hash for Bearer token authentication.

Parameters:

  • token (String)

    the JWT token

Returns:

  • (Hash)

    header hash



55
56
57
# File 'lib/standard_id/testing/request_helpers.rb', line 55

def bearer_auth_header(token)
  { "Authorization" => "Bearer #{token}" }
end

#build_jwt(account: nil, sub: nil, client_id: "test-client", scope: "openid", grant_type: "authorization_code", extra: {}) ⇒ String

Build a JWT token for API/service authentication.

Parameters:

  • account (Object, nil) (defaults to: nil)

    account (uses account.id as sub claim)

  • sub (String, nil) (defaults to: nil)

    explicit subject claim (overrides account.id)

  • client_id (String) (defaults to: "test-client")

    OAuth client ID

  • scope (String) (defaults to: "openid")

    space-separated scopes

  • grant_type (String) (defaults to: "authorization_code")

    OAuth grant type

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

    additional JWT claims

Returns:

  • (String)

    encoded JWT token

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
# File 'lib/standard_id/testing/request_helpers.rb', line 41

def build_jwt(account: nil, sub: nil, client_id: "test-client",
              scope: "openid", grant_type: "authorization_code", extra: {})
  sub ||= &.id
  raise ArgumentError, "account or sub must be provided" if sub.nil?

  claims = { sub: sub, client_id: client_id, scope: scope, grant_type: grant_type }.merge(extra)
  StandardId::JwtService.encode(claims)
end

#create_browser_session(account, user_agent: "RSpec") ⇒ StandardId::BrowserSession

Create a browser session record for integration tests.

For a simpler approach, use stub_web_authentication from AuthenticationHelpers instead.

Parameters:

  • account (Object)

    the account to sign in

  • user_agent (String) (defaults to: "RSpec")

    the user agent string (default: “RSpec”)

Returns:



22
23
24
25
26
27
28
29
# File 'lib/standard_id/testing/request_helpers.rb', line 22

def create_browser_session(, user_agent: "RSpec")
  StandardId::BrowserSession.create!(
    account: ,
    ip_address: "127.0.0.1",
    user_agent: user_agent,
    expires_at: StandardId::BrowserSession.expiry
  )
end