KScript docs
EN

Testing

Testing who may do what

@acting_as() from KScript.Auth sets who @user(), @can() and @authorize() ask about, until the test ends. Pass null to act as a guest. Routes the test calls with @api(/...) see the same user, including routes behind auth, auth:session or auth:token middleware, so a signed-in route needs no token in a test:

<import package="KScript.Auth" />
<import package="KScript.Net" />

<test name="the dashboard greets me">
  <do>@acting_as(@register('ada@example.test', 'correct-horse-battery-9'))</do>
  <expect value="@api(/dashboard).status" equals="200" />
</test>
import KScript.Auth
import KScript.Net

test(name: 'the dashboard greets me') {
  @acting_as(@register('ada@example.test', 'correct-horse-battery-9'))
  expect(@api(/dashboard).status, equals: 200)
}

To test cookie-keyed behaviour, such as a guest's board or a remembered preference, send the cookie yourself: @api(/, options: { headers: { Cookie: 'sb_guest=0f8f' } }). The response's .cookies shows the cookies it set.

<import package="KScript.Auth" />
<import package="KScript.Data" />
<import path="../models/post.kscript" />

<test name="only the author may update a post">
  <let name="post" value="Post->create(title: 'Mine', author_id: 1)" />

  <do>@acting_as({ id: 1 })</do>
  <expect value="@can(update, $post)" equals="true" />

  <do>@acting_as({ id: 2 })</do>
  <expect value="@can(update, $post)" equals="false" />
</test>
import KScript.Auth
import KScript.Data
import "../models/post.kscript"

test(name: 'only the author may update a post') {
  $post = Post->create(title: 'Mine', author_id: 1)

  @acting_as({ id: 1 })
  expect(@can(update, $post), equals: true)

  @acting_as({ id: 2 })
  expect(@can(update, $post), equals: false)
}