Created
March 25, 2021 20:08
-
-
Save yavgel85/15c3c51a747922645652cb6c3dc9933c to your computer and use it in GitHub Desktop.
Set up test traits dynamically #php #laravel #test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Setup: | |
abstract class TestCase extends BaseTestCase | |
{ | |
use CreatesApplication; | |
protected function setUp(): void | |
{ | |
// Set up traits dynamically. | |
// Uses the naming convention: "setUpNameOfMyTrait". | |
$this->afterApplicationCreated(function () { | |
foreach (class_uses_recursive($this) as $trait) { | |
if (method_exists($this, $method = 'setUp' . class_basename($trait))) { | |
call_user_func([$this, $method]); | |
} | |
} | |
}); | |
parent::setUp(); | |
} | |
} | |
// Usage: | |
trait Authenticated | |
{ | |
protected $user; | |
// This will be automatically set up on test classes that uses this trait. | |
public function setUpAuthenticated() | |
{ | |
$this->user = User::factory()->create(); | |
$this->actingAs($this->user); | |
} | |
} | |
/* | |
When cleaning your tests using traits, you often end up having to override the setUp method for each test class that uses the trait in order to initialise some sort of logic. This code enables us to dynamically set up traits when they are used in test classes by using the naming convention: setUpMyTraitName. | |
Note that Laravel already support a similar behaviour for Eloquent trait via the bootMyTraitName convention. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment