Testing with a database
Under kscript test, each test file that uses KScript.Data gets its own database in memory, made from your migrations (or from the models, when there are none yet). Each test's changes are undone when it ends. Your tests don't need $db->create_table(), never touch the project's real database, and never see each other's records:
<!-- tests/post.test.kscript -->
<import package="KScript.Data" />
<import path="../models/post.kscript" />
<test name="a post starts with no views">
<let name="post" value="Post->fake(title: 'Hello')" />
<expect value="$post.views" equals="0" />
<expect value="Post->count()" equals="1" />
</test>
<test name="each test starts empty">
<expect value="Post->count()" equals="0" />
</test>// tests/post.test.kscript
import KScript.Data
import "../models/post.kscript"
test(name: 'a post starts with no views') {
$post = Post->fake(title: 'Hello')
expect($post.views, equals: 0)
expect(Post->count(), equals: 1)
}
test(name: 'each test starts empty') {
expect(Post->count(), equals: 0)
}If you'd rather test against the configured database, set test.database in kscript.json to config. Each test is still undone when it ends. See test.env in Testing.
Fakes
Model->fake() saves a record with made-up values for every field you don't give. ->fake_many() saves several:
<let name="joan" value="Author->fake(name: 'Joan')" />
<let name="posts" value="Post->fake_many(3, author: $joan)" />$joan = Author->fake(name: 'Joan')
$posts = Post->fake_many(3, author: $joan)The made-up values fit each field's type and rules: a string(min: 3, max: 12) is 3 to 12 characters, an email ends in @example.com, and an enum is its first value. A required relation gets a fake record of its own.
Counting queries
A page that sends one query per row gets slow as the data grows. @queries() is the SQL sent so far in the test, each as { sql, bindings, database }, so you may check how many queries a page needs:
<test name="the post list loads authors at once">
<do>Post->fake_many(10)</do>
<do>Post->with(author)->get()</do>
<expect value="@queries()" count_at_most="2" />
</test>test(name: 'the post list loads authors at once') {
Post->fake_many(10)
Post->with(author)->get()
expect(@queries(), count_at_most: 2)
}