and have you tried by calling the parent class method before?
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
self::$adminUser = User::factory()->withRole('admin')->create();
}
I have a laravel 8 project. I want to create a new user using factory with specific role e.g. admin, to be used for the entire class of tests. I am trying to do this using setUpBeforeClass().
Here is what I have so far:
PostPagesTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use App\Models\User;
class PostPagesTest extends TestCase
{
protected $adminUser;
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
self::$adminUser = User::factory()->withRole('admin')->create(); // works under tinker
}
public function test_index_page_visible_as_admin()
{
$response = $this->actingAs($this->adminUser)
->get('/posts')
->assertSeeText('Posts')
->assertStatus(200);
}
public function test_create_page_visible_as_admin()
{
$response = $this->actingAs($this->adminUser)
->get('/posts/create')
->assertStatus(200);
}
}
Unfortunately, when I run the test using php artisan test --filter=PostPagesTest I get the following error:
Call to a member function connection() on null
at C:\project\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1653
1649▕ * @return \Illuminate\Database\Connection
1650▕ */
1651▕ public static function resolveConnection($connection = null)
1652▕ {
➜ 1653▕ return static::$resolver->connection($connection);
1654▕ }
1655▕
1656▕ /**
1657▕ * Get the connection resolver instance.
Any ideas on how I can do this i.e. create an admin user and use it through my tests.
Please or to participate in this conversation.