I want to make a Trait that does something in the beforeAll of the test.
Is it possible to use the beforeAll() function in a trait? And then call uses(Trait::class) in the test case? I was having problem with that..
Also I tried to use PHPUnit TestCase methods like setUp and setUpBeforeClass, but it says that it conflicts with Pest's TestCaseFactory..
@albertpratomo not sure if you have found a workaround for you use case yet, but I have been sharing closures through static constructors, like so (note that this is just sample/pseudo-code and not specific to any framework)
namespace YourApp\Test;
final class Setup
{
public static function logout(): Closure
{
return fn (): void => auth()->logout();
}
public static function rollback(): Closure
{
return fn (): void => DB::rollback();
}
public static function txn(): Closure
{
return fn (): void => DB::beginTransaction();
}
}
and used like so
beforeEach(Setup::txn());
afterEach(Setup::rollback());
I haven't really needed to in my own project, _yet_, but if you were to need more than one to run, you could easily compose them, and just pass the final closure to beforeEach, beforeAll, etc.
You could probably even, as an invokable object just autoload the setups you need instead of one with static methods, like so, while maintaining composability since at the core you're just dealing in closures (i.e., callables).
namespace YourApp\Test\Setup;
final class MyFeatureSetup
{
public function __invoke(): void
{
// check & call all the stuff you need to here;
}
}
and then use it like;
beforeEach(new MyFeatureSetup());
Sharing setup like this is probably safer than hiding the before* and after* calls within a trait of some kind, opting for a more explicit than implicit flow.
Hope this helps!
@jordanbrauer Would be cool to actually have something to allow to configure global beforeBeachs...
uses()->beforeEach(fn () => ...)->in('folder');
Woah, that would be cool (still explicit too)! I guess you would just configure/call that in the Pest.php file?
Correct. Let me know if you are up to work on it.
Correct. Let me know if you are up to work on it.
Sure thing, I'll take a crack at it! I'll get started ASAP , likely next weekend.
Worked started in #282. Started with a little PoC with beforeEach.
Released.
Most helpful comment
Sure thing, I'll take a crack at it! I'll get started ASAP , likely next weekend.