Skip to content

Commit

Permalink
feat: apply WithStory attribute at class level
Browse files Browse the repository at this point in the history
  • Loading branch information
nikophil committed Dec 2, 2024
1 parent 651821e commit 7e09d56
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/PHPUnit/BuildStoryOnTestPrepared.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,20 @@ public function notify(Event\Test\Prepared $event): void
if (!$test->isTestMethod()) {
return;
}

/** @var Event\Code\TestMethod $test */

$method = (new \ReflectionMethod($test->className(), $test->methodName()));
$withStoryReflectionAttributes = $method->getAttributes(WithStory::class);
$withStoryAttributes = [
...(new \ReflectionClass($test->className()))->getAttributes(WithStory::class),
...(new \ReflectionMethod($test->className(), $test->methodName()))->getAttributes(WithStory::class),
];

if (!$withStoryReflectionAttributes) {
if (!$withStoryAttributes) {
return;
}

$withStoryAttributes = array_map(static fn(\ReflectionAttribute $a): WithStory => $a->newInstance(), $withStoryReflectionAttributes);
foreach ($withStoryAttributes as $withStoryAttribute) {
$withStoryAttribute->story::load();
$withStoryAttribute->newInstance()->story::load();
}
}
}
48 changes: 48 additions & 0 deletions tests/Integration/Attribute/WithStory/WithStoryOnClassTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

declare(strict_types=1);

namespace Integration\Attribute\WithStory;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Zenstruck\Foundry\Attribute\WithStory;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;
use Zenstruck\Foundry\Tests\Fixture\Factories\Entity\GenericEntityFactory;
use Zenstruck\Foundry\Tests\Fixture\Stories\EntityPoolStory;
use Zenstruck\Foundry\Tests\Fixture\Stories\EntityStory;

#[WithStory(EntityStory::class)]
final class WithStoryOnClassTest extends KernelTestCase
{
use Factories, ResetDatabase;

/**
* @test
*/
public function can_use_story_in_attribute(): void
{
GenericEntityFactory::assert()->count(2);

// ensure state is accessible
$this->assertSame('foo', EntityStory::get('foo')->getProp1());
}

/**
* @test
*/
#[WithStory(EntityStory::class)]
public function can_use_story_in_attribute_multiple_times(): void
{
GenericEntityFactory::assert()->count(2);
}

/**
* @test
*/
#[WithStory(EntityPoolStory::class)]
public function can_use_another_story_at_level_class(): void
{
GenericEntityFactory::assert()->count(5);
}
}

0 comments on commit 7e09d56

Please sign in to comment.