Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 25, 2021 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yavgel85/15c3c51a747922645652cb6c3dc9933c to your computer and use it in GitHub Desktop.
Save yavgel85/15c3c51a747922645652cb6c3dc9933c to your computer and use it in GitHub Desktop.
Set up test traits dynamically #php #laravel #test
<?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