Community编程与开发github.com

Taldres/laravel-waitlist:编写集成测试

为使用 taldres/laravel-waitlist 包的应用编写功能测试:从事件中获取明文令牌,断言确认邮件和其他邮件,测试 PHP 中以及通过包 HTTP 路由的注册、确认和取消订阅流程,并在测试中绕过速率限制和机器人检查。

laravel-waitlist:编写集成测试 是什么?

该技能指导开发者如何为集成了 `taldres/laravel-waitlist` 包的应用编写功能测试。它专注于测试应用自身围绕等待列表(waitlist)的代码,而不是包本身。技能涵盖了测试的所有关键环节:设置测试环境(包括迁移、加密密钥、配置选项)、通过包的公共 API 添加用户并获取明文确认/取消订阅令牌、断言邮件发送、测试 HTTP 路由(包括处理令牌验证和错误响应),以及通过回调模拟绕过机器人检查和数据擦除。它还提供了最佳实践和反模式,例如强调应通过 `add()` 方法和事件来操作,而不是直接使用工厂或数据库列。该技能适用于 Laravel 框架的 PHPUnit 测试,详细说明了如何利用 `Event::fake()`、`Mail::fake()`、`RefreshDatabase` 等 Laravel 测试工具来隔离和验证功能。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Taldres/laravel-waitlist/tree/HEAD/resources/boost/skills/laravel-waitlist-testing

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Laravel Waitlist:测试集成

当为使用 taldres/laravel-waitlist 的应用编写或修复测试时使用此技能:测试其表单、监听器、邮件和页面,而不是包本身。

主要目标

  • 通过包的公共 API 测试应用自身围绕等待列表的代码,使用真实的令牌和真实的状态变更

工作流

1. 设置

  • 包的迁移文件已发布到 database/migrations,因此 RefreshDatabase 会创建这些表。
  • 必须在测试环境中设置 APP_KEY:地址会被加密,并使用从它派生的密钥进行查找。
  • 事件实现了 ShouldDispatchAfterCommit;配合 RefreshDatabase,它们仍然正常派发。
  • 包的路由在启动时注册。要测试它们,请在 phpunit.xml 或 .env.testing 中设置 WAITLIST_ROUTES_ENABLED=true;在测试内部调用 config()->set() 为时已晚。空的 WAITLIST_ROUTES_ENABLED= 是配置错误;关闭的路由返回 404。
  • 应用的 WaitlistServiceProvider 在测试中启动,因此其列表、字段和页面都存在。在测试内调用 Waitlist::define() 会仅为该测试替换该项目;下一个测试会再次启动应用并加载提供者的定义。
  • 使用枚举中的键(而非字符串)设置其他包配置:config()->set(ConfigKey::DoubleOptIn->value, false) (Taldres\Waitlist\Enums\ConfigKey;默认值位于包的 config/waitlist.php 中)。
  • 设置错误会抛出 InvalidConfigurationException,绝不会抛出 WaitlistException;断言它,不要在应用代码中捕获它。配置值未读取时也是如此,需要指明键名:null 表示从不或关闭,代表“永远”的数字会被拒绝(链接不能在 2038-01-19 之后过期,保留期不能回退到 1970 年之前)。

2. 回传表单显示的内容

措辞可以是一个文本或每个区域一个文本;按服务版本和区域回传:

use Taldres\Waitlist\Facades\Waitlist;
use Taldres\Waitlist\Support\PurposeWording;

$purposes = collect(Waitlist::purposes('beta'))
    ->filter(fn (PurposeWording $wording) => $wording->required)   // 根据测试需要添加可选的
    ->mapWithKeys(fn (PurposeWording $wording) => [$wording->purpose => ['version' => $wording->version, 'locale' => $wording->locale]])
    ->all();

$result = Waitlist::for('beta')->add('[email protected]', $purposes);

3. 获取明文令牌

明文确认令牌仅存在于启用了双重确认的列表的 EntrySubscribed 负载中。取消订阅和管理令牌也来自 Waitlist::unsubscribeToken($entry)->token 和 Waitlist::manageLink($entry)->token。

use Illuminate\Support\Facades\Event;
use Taldres\Waitlist\Enums\EntryStatus;
use Taldres\Waitlist\Events\EntrySubscribed;

Event::fake([EntrySubscribed::class]);

Waitlist::for('beta')->add('[email protected]', $purposes);

$event = Event::dispatched(EntrySubscribed::class)->first()[0];

$entry = Waitlist::confirm($event->confirmToken);
expect($entry->status)->toBe(EntryStatus::Confirmed);   // 或 $this->assertSame(...)

为了保持真实监听器运行(例如邮件监听器)并仍然捕获令牌,请使用监听而非伪造:

$token = null;
Event::listen(function (EntrySubscribed $event) use (&$token) {
    $token = $event->confirmToken;
});

对于取消订阅测试,$event->unsubscribeToken 作用相同;对于偏好页面,使用 ManageLinkRequested::$manageToken。

在设置了 ->doubleOptIn(false) 的列表上(或 waitlist.double_opt_in.enabled 关闭时),EntrySubscribed 会以 requiresConfirmation 为 false 且 confirmToken 为 null 触发,随后触发 EntryConfirmed;条目已经确认。被 max_pending_per_address 阻止的注册根本不会触发 EntrySubscribed($result->outcome 是 confirmation_deferred)。

4. 断言邮件

use Illuminate\Support\Facades\Mail;

Mail::fake();

Waitlist::for('beta')->add('[email protected]', $purposes);

Mail::assertSent(ConfirmWaitlistMail::class, fn ($mail) => $mail->hasTo('[email protected]'));

队列监听器在 QUEUE_CONNECTION=sync(Laravel 的测试默认设置)下会内联运行。

5. HTTP 路由

use Illuminate\Routing\Middleware\ThrottleRequests;

$this->withoutMiddleware(ThrottleRequests::class);   // 从一个测试 IP 进行多次注册
Event::fake([EntrySubscribed::class]);

$wording = $this->getJson('/waitlist/purposes?list=beta')->assertOk()->json('data.0');

$this->postJson('/waitlist', [
    'email' => '[email protected]',
    'list' => 'beta',
    'purposes' => [$wording['purpose'] => ['version' => $wording['version'], 'locale' => $wording['locale']]],
])->assertStatus(202);

$token = Event::dispatched(EntrySubscribed::class)->first()[0]->confirmToken;

$this->postJson("/waitlist/confirm/{$token}")->assertOk()->assertJsonPath('data.status', 'confirmed');
$this->getJson('/waitlist/confirm/unknown')->assertNotFound()->assertJsonPath('error', 'invalid_token');

包自身的拒绝会命名一个 error(invalid_token、expired_token、unknown_list、not_subscribed、list_unavailable)。断言它:没有 error 的 404 是错误的 URL、关闭的路由或 useWaitlist 门卫,并且对于未知令牌会通过 assertNotFound()。

只有 HTTP 注册会应用项目的字段;add() 信任其调用者。在测试中定义它们以断言 422:

use Taldres\Waitlist\Definitions\ProjectDefinition;

Waitlist::define(function (ProjectDefinition $project): void {
    $project->purpose('waitlist', ['v1' => '请给我发邮件。']);
    $project->list('teams', purpose: 'waitlist')->fields(['contact_phone' => ['required']]);
});

$this->postJson('/waitlist', [/* email, list, purposes */])->assertJsonValidationErrors('metadata.contact_phone');

使用 postJson()/getJson():如果没有 Accept: application/json,项目 urls() 中的页面会将答案变成重定向。

6. 机器人检查和数据擦除

use Taldres\Waitlist\Events\EntryForgotten;

Waitlist::verifySpamUsing(fn () => true);    // 在测试中绕过 Turnstile 等
Waitlist::verifySpamUsing(fn () => false);   // 断言 422 “垃圾检查失败。”
Waitlist::verifySpamUsing(null);             // 恢复为已配置的保护器

Event::fake([EntryForgotten::class]);
Waitlist::allProjects()->forget('[email protected]');
Event::assertDispatched(EntryForgotten::class, fn (EntryForgotten $event) => $event->email === '[email protected]');

规则、参考和模板

  • 通过公共 API 断言状态:$entry->status、hasConsentFor()、Waitlist::for($list)->snapshot()、recipients()->count()。
  • 注册的结果:$result->outcome(SubscribeOutcome:started、confirmation_resent、resend_suppressed、already_confirmed、resubscribed、confirmation_deferred)。
  • 通过 HTTP,注册对于新地址和已知地址都返回 202;断言状态,而不是响应体。

示例

  • “测试注册发送确认邮件”:第 2 和第 4 步。
  • “测试确认页面”:第 3 和第 5 步,或使用捕获的令牌调用控制器路由。
  • “测试简报只发送给同意的人”:注册两个地址,一个带有可选目的,确认两者,断言 Waitlist::recipients('newsletter')->count() === 1。

反模式

  • 使用工厂或 create() 创建 WaitlistEntry、订阅或同意;应使用 add() 和令牌方法,否则会跳过事件和不变量。
  • 从数据库列读取令牌;应使用事件或 Waitlist::unsubscribeToken() 和 Waitlist::manageLink()。
  • 在测试内部使用 config()->set() 启用路由。
  • 在断言确认邮件的测试中伪造 EntrySubscribed。
  • 使用箭头函数捕获令牌:它们按值捕获。

Individual skills in this repo

This repo contains 13 individual skills — each has its own dedicated page.

Taldres/laravel-waitlist

Use this skill when reviewing Laravel package compatibility across composer constraints, PHP versions, Laravel versions, Testbench versions, dependency stability lanes, Windows CI, or matrix-sensitive code and workflow changes.

Taldres/laravel-waitlist

Use this skill when creating or updating the bundled Laravel Boost skill under resources/boost/skills from the package implementation and package documentation. Trigger after public APIs, commands, config, routes, views, publish tags, README content, or examples change.

Taldres/laravel-waitlist

Use this skill when preparing Laravel package releases: CHANGELOG.md updates, generated release notes, GitHub release workflows, version checks, tags, release validation, or release automation changes. Never publish autonomously.

Taldres/laravel-waitlist

Use this skill when adding Laravel package capabilities or wiring them through the service provider: commands, migrations, routes, config merges, views, translations, assets, middleware, publish tags, workbench files, or console-only behavior.

Taldres/laravel-waitlist

Use this skill when writing, editing, fixing, or reviewing package tests with Pest 4/5 and Orchestra Testbench, including TDD, feature tests, unit tests, type coverage, arch tests, workbench behavior, commands, routes, config, migrations, and publishable resources.

Taldres/laravel-waitlist

Integrate taldres/laravel-waitlist in a Laravel application: define purposes, lists and fields, build the signup form, send the confirmation mail from events, add a preference page, and keep consent, retention and encryption intact.

Taldres/laravel-waitlist

Build the pages of a taldres/laravel-waitlist integration: the signup form with the registered wording, and the confirm, unsubscribe and preference pages, either in Laravel controllers (Blade, Livewire, Inertia) or in an SPA or static site over the package's JSON API, including CORS and bot protection.

Taldres/laravel-waitlist

Turn a taldres/laravel-waitlist waitlist into a launch: invite people in batches in signup order, let invited addresses register, announce the launch to everyone who agreed, and erase the list once its purpose is fulfilled.

Taldres/laravel-waitlist

Send the mails of a taldres/laravel-waitlist integration: the double opt-in confirmation, the preference page link, a welcome mail, launch mails and newsletters to the people who agreed, with the right unsubscribe links, one-click headers and a sender per project.

Taldres/laravel-waitlist

Operate a taldres/laravel-waitlist installation: answer access and erasure requests, withdraw a purpose on request, apply retention, erase a list once its purpose is fulfilled, rotate APP_KEY with waitlist:rekey, export a list, and check the setup before going live.

Taldres/laravel-waitlist

Run the waitlists of several products in one Laravel app with taldres/laravel-waitlist projects: define projects, scope facade calls with project(), resolve the project of HTTP signups, send mail per project, handle requests across all projects, or keep projects in a database for a central waitlist API.

Taldres/laravel-waitlist

Keep a newsletter tool such as Brevo, Mailchimp or Mailcoach in step with a taldres/laravel-waitlist waitlist: add confirmed contacts per purpose, remove them on withdrawal and erasure, and carry unsubscribes made at the provider back into the waitlist via a webhook.

Taldres/laravel-waitlist

Build waitlist statistics with taldres/laravel-waitlist: signups and confirmations per day for charts, totals and confirmation rates for a period, the confirmed count on any past day, and how many people are on a list right now, for dashboards, admin pages and API endpoints.

相关技能