Write CI4 feature tests with DatabaseTestTrait, FeatureTestTrait, withSession(), and seeInDatabase().
Testing in CI4
// tests/Feature/PostTest.php
use CodeIgniterTestCIUnitTestCase;
use CodeIgniterTestDatabaseTestTrait;
use CodeIgniterTestFeatureTestTrait;
class PostTest extends CIUnitTestCase {
use DatabaseTestTrait, FeatureTestTrait;
protected $migrate = true;
protected $seed = "TestSeeder";
public function testGuestCannotCreatePost(): void {
$result = $this->call("POST", "/posts", [
"title" => "Test Post",
"body" => "Test body",
]);
$result->assertStatus(302);
$result->assertRedirectTo("/login");
}
public function testAuthUserCanCreatePost(): void {
$this->withSession(["logged_in" => true, "user_id" => 1]);
$result = $this->call("POST", "/posts", [
"title" => "Test Post",
"body" => "Body content",
]);
$result->assertStatus(302);
$this->seeInDatabase("posts", ["title" => "Test Post"]);
}
}
// Run
php spark test