How to move function from closure to normal function
P粉831310404
2023-09-05 21:54:44
<p>I'm trying to make the pest test files easier to read. </p>
<p>Currently, I have some standard tests: </p>
<pre class="brush:php;toolbar:false;">test('can get subscribers latest subscription', function () {
$this->seed(PlansTestSeeder::class);
$this->seed(SubscriptionsTestSeeder::class);
$this->assertDatabaseCount('plans', 2);
$this->assertDatabaseCount('subscriptions', 0);
Subscription::factory()->create([
"plan_id" => Plan::where("slug", "bronze")->first()->id
]);
Subscription::factory()->create([
"plan_id" => Plan::where("slug", "silver")->first()->id
]);
Subscription::factory()->create([
"plan_id" => Plan::where("slug", "silver")->first()->id,
"status" => "expired"
]);
Subscription::factory()->trashed()->create();
$this->assertDatabaseCount('subscriptions', 4);
});
test('can get subscribers active subscriptions', function () {
$this->seed(PlansTestSeeder::class);
$this->seed(SubscriptionsTestSeeder::class);
$silverPlan = Plan::where("slug", "silver")->first();
$subscription1 = Subscription::factory()->create([
"plan_id" => Plan::where("slug", "silver")->first()->id,
"subscriber_id" => 1,
"subscriber_type" => "ApresourcingFramework\Billing\Tests\Models\Subscriber",
"created_at" => now()->subDays(2),
"started_at" => now()->subDays(2)
]);
$subscription2 = Subscription::factory()->create([
"plan_id" => $silverPlan->id,
"subscriber_id" => 1,
"subscriber_type" => "ApresourcingFramework\Billing\Tests\Models\Subscriber",
"created_at" => now()->subDays(1),
"started_at" => now()->subDays(1)
]);
$user = Subscriber::find(1);
$subscription = $user->latestSubscription();
expect($subscription->id)->toBe($subscription2->id);
});</pre>
<p>But to remind myself which tests I wrote, I have to scroll up and down the page over and over again.</p>
<p>What I want to do is change it to something like this: </p>
<pre class="brush:php;toolbar:false;">test('can get subscribers latest subscription', getLatestSubscription());
test('can get subscribers active subscriptions', getActiveSubscriptions());
function getLatestSubscription() {
/// function code here
});
function getActiveSubscriptions() {
// function code here
});</pre>
<p>However, the test function contains a reference to $this which is available in the normal closure but not in the standard function because I set it there. </p>
<p>Edit: I'm using the laravel pest plugin - I'm not sure if this has an impact on the use of $this</p>
<p>Is there any way to solve this problem? </p>
Thanks for some tips in the reply. Not as neat as I'd hoped, but at least it means all test ("test description") calls are in one place at the bottom of the php file.