Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added Admin E2E tests

Damian Legawiec3c1f1e162c34
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 228422409e..687ba2a0dc 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -23,6 +23,7 @@ Please read our [Code of Conduct](../CODE_OF_CONDUCT.md) before contributing.
- [Packages](#packages)
- [Common commands](#common-commands)
- [Package-specific commands](#package-specific-commands)
+ - [Admin SPA E2E tests](#admin-spa-e2e-tests)
- [Type generation](#type-generation)
- [Releasing packages](#releasing-packages)
- [Code Style](#code-style)
@@ -181,7 +182,7 @@ After schema changes, re-run `bundle exec rake parallel_setup` to update the wor
### Integration tests (Admin Panel)
-The Admin Panel uses feature specs that run in a real browser via chromedriver. You only need this if you're working on admin UI changes.
+The legacy Rails admin (`spree/admin`) ships feature specs that run in a real browser via chromedriver. You only need this if you're touching the legacy admin UI.
Install chromedriver on macOS:
@@ -189,6 +190,8 @@ Install chromedriver on macOS:
brew install chromedriver
```
+The 6.0 React admin SPA (`packages/admin`) has its own end-to-end test suite running on Playwright against a real Rails backend — see [Admin SPA E2E tests](#admin-spa-e2e-tests) under TypeScript Development.
+
### Performance in development mode
You may notice that your Spree store runs slower in development environment. This is caused by disabled caching and automatic reloading of code after each change.
@@ -256,6 +259,42 @@ pnpm --filter @spree/sdk generate:zod
Tests use [Vitest](https://vitest.dev/) with [MSW](https://mswjs.io/) for API mocking at the network level.
+### Admin SPA E2E tests
+
+The 6.0 React admin (`packages/admin`) has an end-to-end suite running on [Playwright](https://playwright.dev/) against a real Rails backend — no mocks. The spec files exercise the full UI: login form, staff invitation flow, invitee signup. CI runs the same suite via the `admin-e2e` job in `.github/workflows/packages.yml`.
+
+To run locally you need Ruby (the suite boots a Rails server) and a one-time browser install:
+
+```bash
+# Make sure the dummy Rails app exists (one-time, after a fresh checkout).
+cd spree/api
+bundle install
+bundle exec rake test_app
+
+# Install Playwright's Chromium (one-time per machine).
+cd ../../packages/admin
+pnpm test:e2e:install
+
+# Run the suite. Boots Rails on :3010 + Vite on :5174, runs all specs, tears
+# both down. Safe to re-run repeatedly — the SQLite DB resets each run.
+pnpm test:e2e
+```
+
+For interactive debugging (time-travel through actions, inspect the DOM at each step):
+
+```bash
+pnpm test:e2e:ui
+```
+
+Filter to a single spec or test name:
+
+```bash
+pnpm test:e2e e2e/auth.spec.ts
+pnpm test:e2e -g "invites a teammate"
+```
+
+When a test fails, Playwright drops a screenshot, video, and DOM snapshot in `packages/admin/test-results/<spec>/` — usually enough to diagnose without re-running.
+
### Type generation
TypeScript types in `packages/sdk/src/types/generated/` are auto-generated from the Rails API serializers using [typelizer](https://github.com/skryukov/typelizer). To regenerate after changing serializers:
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml
index 72f7b9e92d..be24776909 100644
--- a/.github/workflows/packages.yml
+++ b/.github/workflows/packages.yml
@@ -85,6 +85,80 @@ jobs:
working-directory: packages/sdk
run: pnpm test:integration
+ admin-e2e:
+ name: "Admin SPA - E2E"
+ runs-on: ubuntu-latest
+ env:
+ RAILS_ENV: test
+ DB: sqlite3
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: ruby/setup-ruby@v1
+ with:
+ ruby-version: '4.0'
+ bundler-cache: true
+ working-directory: spree/api
+
+ - uses: pnpm/action-setup@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: pnpm
+
+ - run: pnpm install --frozen-lockfile
+
+ # The admin SPA imports built dist from the SDKs (per the workspace
+ # convention) — build them first so Vite resolves the workspace deps.
+ - name: Build SDK dependencies
+ run: pnpm turbo build --filter=@spree/sdk-core --filter=@spree/admin-sdk
+
+ - name: Setup dummy Rails app
+ working-directory: spree/api
+ run: bundle exec rake test_app
+
+ # Cache the chromium download (~85MB). The cache key tracks the
+ # Playwright version pinned in lockfile, so a bump auto-invalidates.
+ - name: Read Playwright version
+ id: playwright
+ run: |
+ VERSION=$(node -p "require('./packages/admin/node_modules/@playwright/test/package.json').version")
+ echo "version=$VERSION" >> $GITHUB_OUTPUT
+
+ - name: Cache Playwright browsers
+ id: playwright-cache
+ uses: actions/cache@v4
+ with:
+ path: ~/.cache/ms-playwright
+ key: playwright-${{ runner.os }}-${{ steps.playwright.outputs.version }}
+
+ - name: Install Playwright browsers
+ if: steps.playwright-cache.outputs.cache-hit != 'true'
+ working-directory: packages/admin
+ run: pnpm exec playwright install --with-deps chromium
+
+ # Even on a cache hit Playwright still wants the OS-level deps installed
+ # (libnss, libxkbcommon, …). `install-deps` is the cheap part.
+ - name: Install Playwright OS deps
+ if: steps.playwright-cache.outputs.cache-hit == 'true'
+ working-directory: packages/admin
+ run: pnpm exec playwright install-deps chromium
+
+ - name: Run admin E2E tests
+ working-directory: packages/admin
+ run: pnpm test:e2e
+
+ - name: Upload Playwright report
+ if: failure()
+ uses: actions/upload-artifact@v4
+ with:
+ name: playwright-report
+ path: |
+ packages/admin/playwright-report/
+ packages/admin/test-results/
+ retention-days: 14
+
release-sdk:
name: "SDK - Release"
needs: check
diff --git a/packages/admin/.gitignore b/packages/admin/.gitignore
index 7ceb59f89a..daa2dde29d 100644
--- a/packages/admin/.gitignore
+++ b/packages/admin/.gitignore
@@ -23,3 +23,10 @@ dist-ssr
*.sln
*.sw?
.env
+
+# Playwright
+/test-results/
+/playwright-report/
+/playwright/.cache/
+/e2e/.credentials.json
+/e2e/.rails.pid
diff --git a/packages/admin/README.md b/packages/admin/README.md
index df873428b9..4296f25ac7 100644
--- a/packages/admin/README.md
+++ b/packages/admin/README.md
@@ -59,6 +59,9 @@ VITE_SPREE_API_URL=https://api.mystore.com pnpm build
| `pnpm lint` | Lint with Biome |
| `pnpm lint:fix` | Lint and auto-fix with Biome |
| `pnpm format` | Format source with Biome |
+| `pnpm test:e2e` | Run the Playwright E2E suite against a real Rails backend |
+| `pnpm test:e2e:ui` | Run the E2E suite in Playwright's interactive UI for debugging |
+| `pnpm test:e2e:install` | One-time: install the Chromium build Playwright drives |
## Project structure
@@ -161,6 +164,61 @@ export function useOrders(params: ListOrdersParams) {
Mutations follow the same pattern with `useMutation` and `queryClient.invalidateQueries(...)` to refresh affected views.
+## End-to-end tests
+
+The `e2e/` folder holds [Playwright](https://playwright.dev/) specs that drive the SPA against a real Rails backend — no API mocks. CI runs the same suite via the `admin-e2e` job in `.github/workflows/packages.yml`; locally, `pnpm test:e2e` mirrors what CI does.
+
+What the suite boots:
+
+- **Rails** on `:3010` — the dummy app at `spree/api/spec/dummy`, with a fresh SQLite DB seeded via `Spree::Seeds::All` on every run.
+- **Vite dev server** on `:5174` — proxies `/api/*` to the test Rails so the SPA stays same-origin (matches dev's cookie posture exactly).
+- **Playwright** drives Chromium and tears both down at the end.
+
+Currently covered:
+
+- `e2e/auth.spec.ts` — login form happy path + invalid-credentials error
+- `e2e/invitation-acceptance.spec.ts` — full staff-onboarding lifecycle: admin signs in → opens Settings → Staff → invites a teammate → logs out → invitee opens the link in a fresh browser context → completes signup → lands authenticated
+
+### Running locally
+
+One-time prerequisites: a built dummy Rails app and the Chromium browser bundle.
+
+```bash
+# From the repo root, build the dummy Rails app once.
+cd spree/api
+bundle install
+bundle exec rake test_app
+
+# From this package, install Playwright's Chromium once per machine.
+cd ../../packages/admin
+pnpm test:e2e:install
+```
+
+Then run the suite:
+
+```bash
+pnpm test:e2e # full suite
+pnpm test:e2e e2e/auth.spec.ts # one file
+pnpm test:e2e -g "invites a teammate" # filter by test name
+pnpm test:e2e:ui # interactive debugger (time-travel, DOM inspector)
+```
+
+`pnpm test:e2e` is safe to re-run: each run resets the SQLite DB before seeding, so tests start from a known state.
+
+### Debugging failures
+
+On failure, Playwright drops three artifacts in `test-results/<spec>/`:
+
+- `test-failed-1.png` — screenshot at the moment of failure
+- `video.webm` — the full run
+- `error-context.md` — DOM snapshot + the failing locator (usually enough to fix selector issues without re-running)
+
+CI uploads these as a `playwright-report` artifact (14-day retention) on failed runs.
+
+### Adding a spec
+
+Specs live next to the existing ones in `e2e/`. Use `getCredentials()` from `e2e/fixtures.ts` for the seeded admin email/password and store ID — anything else, drive through the UI like a user would. Avoid hitting the Admin API directly from a spec unless the flow you're testing requires backend setup that has no UI path; the value of these tests is exercising the full layer cake.
+
## Contributing
This package is private and ships as part of the Spree 6.0 release. Architecture decisions live in `docs/plans/6.0-admin-spa.md` — please read that before proposing significant changes.
diff --git a/packages/admin/e2e/auth.spec.ts b/packages/admin/e2e/auth.spec.ts
new file mode 100644
index 0000000000..421c5b5f5b
--- /dev/null
+++ b/packages/admin/e2e/auth.spec.ts
@@ -0,0 +1,31 @@
+import { expect, test } from '@playwright/test'
+import { getCredentials } from './fixtures'
+
+test.describe('admin authentication', () => {
+ test('signs in via the login form and lands on the dashboard', async ({ page }) => {
+ const creds = getCredentials()
+
+ await page.goto('/login')
+ await expect(page.getByText(/welcome back/i)).toBeVisible()
+
+ await page.getByLabel(/email/i).fill(creds.admin_email)
+ await page.getByLabel(/password/i).fill(creds.admin_password)
+ await page.getByRole('button', { name: /^login$/i }).click()
+
+ // The /_authenticated/ index resolves the active store and redirects to
+ // /$storeId. We just need to leave /login.
+ await expect(page).not.toHaveURL(/\/login/, { timeout: 15_000 })
+ await expect(page.url()).not.toContain('/login')
+ })
+
+ test('rejects invalid credentials with an inline error', async ({ page }) => {
+ await page.goto('/login')
+
+ await page.getByLabel(/email/i).fill('[email protected]')
+ await page.getByLabel(/password/i).fill('wrong-password-123')
+ await page.getByRole('button', { name: /^login$/i }).click()
+
+ await expect(page.getByText(/invalid email or password/i)).toBeVisible()
+ expect(page.url()).toContain('/login')
+ })
+})
diff --git a/packages/admin/e2e/fixtures.ts b/packages/admin/e2e/fixtures.ts
new file mode 100644
index 0000000000..abbb1ea9a1
--- /dev/null
+++ b/packages/admin/e2e/fixtures.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs'
+import { CREDENTIALS_FILE } from './paths'
+
+export interface E2ECredentials {
+ api_url: string
+ admin_email: string
+ admin_password: string
+ store_id: string
+ store_name: string
+}
+
+let cached: E2ECredentials | null = null
+
+export function getCredentials(): E2ECredentials {
+ if (!cached) {
+ cached = JSON.parse(readFileSync(CREDENTIALS_FILE, 'utf-8'))
+ }
+ return cached!
+}
diff --git a/packages/admin/e2e/global-setup.ts b/packages/admin/e2e/global-setup.ts
new file mode 100644
index 0000000000..5e9041a353
--- /dev/null
+++ b/packages/admin/e2e/global-setup.ts
@@ -0,0 +1,86 @@
+import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
+import { unlinkSync, writeFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { CREDENTIALS_FILE, E2E_DIR, RAILS_PID_FILE } from './paths'
+
+const API_GEM_DIR = resolve(E2E_DIR, '../../../spree/api')
+const PORT = process.env.E2E_RAILS_PORT || '3010'
+// Mirrors `spec/dummy/config/database.yml`.
+const TEST_SQLITE = resolve(API_GEM_DIR, 'spec/dummy/db/spree_test.sqlite3')
+
+const RAILS_ENV = { ...process.env, RAILS_ENV: 'test', PORT }
+
+// One runner invocation pays the Bundler/Rails boot tax once instead of three
+// times. Final `puts` emits the credentials JSON the spec files read.
+const BOOTSTRAP_RUBY = [
+ "load Rails.root.join('db', 'schema.rb').to_s",
+ 'Spree::Seeds::All.call',
+ 'require "json"',
+ 's = Spree::Store.default',
+ 'admin = Spree.admin_user_class.first || Spree.admin_user_class.create!(email: "[email protected]", password: "spree123", password_confirmation: "spree123")',
+ 'admin.update!(password: "spree123", password_confirmation: "spree123")',
+ 's.add_user(admin, Spree::Role.default_admin_role) unless s.role_users.exists?(user: admin)',
+ 'port = ENV.fetch("PORT", 3010)',
+ 'puts JSON.generate(api_url: "http://localhost:#{port}", admin_email: admin.email, admin_password: "spree123", store_id: s.prefixed_id, store_name: s.name)',
+].join('; ')
+
+function rmIfExists(path: string) {
+ try {
+ unlinkSync(path)
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e
+ }
+}
+
+async function waitForServer(url: string, timeoutMs = 30_000): Promise<void> {
+ const start = Date.now()
+ while (Date.now() - start < timeoutMs) {
+ try {
+ const res = await fetch(url)
+ if (res.status < 500) return
+ } catch {
+ /* not ready */
+ }
+ await new Promise((r) => setTimeout(r, 500))
+ }
+ throw new Error(`Server did not start within ${timeoutMs}ms at ${url}`)
+}
+
+let serverProcess: ChildProcess | null = null
+
+export default async function globalSetup() {
+ rmIfExists(TEST_SQLITE)
+
+ // Pass the script via argv to sidestep shell quoting (the Ruby contains
+ // both single and double quotes).
+ const result = spawnSync('bundle', ['exec', 'spec/dummy/bin/rails', 'runner', BOOTSTRAP_RUBY], {
+ cwd: API_GEM_DIR,
+ encoding: 'utf-8',
+ timeout: 120_000,
+ maxBuffer: 10 * 1024 * 1024,
+ env: RAILS_ENV,
+ })
+ if (result.status !== 0) {
+ throw new Error(`Bootstrap runner failed:\n${result.stderr}\n${result.stdout}`)
+ }
+ const jsonMatch = result.stdout.match(/\{.*\}\s*$/)
+ if (!jsonMatch) {
+ throw new Error(`Failed to parse credentials from runner output:\n${result.stdout}`)
+ }
+ writeFileSync(CREDENTIALS_FILE, jsonMatch[0])
+
+ serverProcess = spawn(
+ 'bundle',
+ ['exec', 'spec/dummy/bin/rails', 'server', '-p', PORT, '-e', 'test'],
+ { cwd: API_GEM_DIR, stdio: ['ignore', 'pipe', 'pipe'], env: RAILS_ENV },
+ )
+
+ serverProcess.stderr?.on('data', (data: Buffer) => {
+ const msg = data.toString()
+ if (msg.includes('Error') || msg.includes('error')) console.error('[rails]', msg)
+ })
+
+ if (serverProcess.pid) writeFileSync(RAILS_PID_FILE, String(serverProcess.pid))
+
+ await waitForServer(`http://localhost:${PORT}/api/v3/admin/me`)
+}
diff --git a/packages/admin/e2e/global-teardown.ts b/packages/admin/e2e/global-teardown.ts
new file mode 100644
index 0000000000..6e59ee78bc
--- /dev/null
+++ b/packages/admin/e2e/global-teardown.ts
@@ -0,0 +1,24 @@
+import { readFileSync, unlinkSync } from 'node:fs'
+import { RAILS_PID_FILE } from './paths'
+
+export default async function globalTeardown() {
+ let pid: number
+ try {
+ pid = Number.parseInt(readFileSync(RAILS_PID_FILE, 'utf-8'), 10)
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return
+ throw e
+ }
+
+ try {
+ process.kill(pid, 'SIGTERM')
+ } catch {
+ // Process already dead.
+ }
+
+ try {
+ unlinkSync(RAILS_PID_FILE)
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e
+ }
+}
diff --git a/packages/admin/e2e/invitation-acceptance.spec.ts b/packages/admin/e2e/invitation-acceptance.spec.ts
new file mode 100644
index 0000000000..ad910de4ce
--- /dev/null
+++ b/packages/admin/e2e/invitation-acceptance.spec.ts
@@ -0,0 +1,74 @@
+import { expect, test } from '@playwright/test'
+import { getCredentials } from './fixtures'
+
+test.describe('invitation lifecycle', () => {
+ test('admin invites a teammate and the invitee signs up via the link', async ({
+ page,
+ browser,
+ }) => {
+ const creds = getCredentials()
+ const inviteeEmail = `e2e-invitee-${Date.now()}@example.com`
+
+ await page.goto('/login')
+ await page.getByLabel(/email/i).fill(creds.admin_email)
+ await page.getByLabel(/password/i).fill(creds.admin_password)
+ await page.getByRole('button', { name: /^login$/i }).click()
+ await expect(page).not.toHaveURL(/\/login/, { timeout: 15_000 })
+
+ await page.goto(`/${creds.store_id}/settings/staff`)
+ await expect(page.getByText(/^staff$/i).first()).toBeVisible({ timeout: 15_000 })
+
+ await page.getByRole('button', { name: /invite teammate/i }).click()
+ await expect(page.getByText(/invite teammate/i).first()).toBeVisible()
+
+ await page.getByLabel(/email/i).fill(inviteeEmail)
+ await page.getByLabel(/role/i).click()
+ await page.getByRole('option').first().click()
+
+ const [createResponse] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes('/api/v3/admin/invitations') &&
+ res.request().method() === 'POST' &&
+ res.status() === 201,
+ { timeout: 15_000 },
+ ),
+ page.getByRole('button', { name: /send invitation/i }).click(),
+ ])
+ const invitation = (await createResponse.json()) as { acceptance_url: string }
+ expect(invitation.acceptance_url).toMatch(/\/accept-invitation\//)
+ // Tolerate either path-only (test env, admin_url unset) or absolute URL.
+ const acceptancePath = invitation.acceptance_url.replace(/^https?:\/\/[^/]+/, '')
+
+ await page.getByRole('button', { name: /user menu/i }).click()
+ await page.getByRole('menuitem', { name: /log out/i }).click()
+ await expect(page).toHaveURL(/\/login/, { timeout: 15_000 })
+
+ // Fresh context so the admin's refresh cookie doesn't leak into the invitee session.
+ const inviteeContext = await browser.newContext()
+ const inviteePage = await inviteeContext.newPage()
+ try {
+ await inviteePage.goto(acceptancePath)
+ await expect(inviteePage.getByText(new RegExp(`join ${creds.store_name}`, 'i'))).toBeVisible({
+ timeout: 15_000,
+ })
+ await expect(inviteePage.getByLabel(/email/i)).toHaveValue(inviteeEmail)
+
+ await inviteePage.getByLabel(/first name/i).fill('Pat')
+ await inviteePage.getByLabel(/last name/i).fill('Carlson')
+ await inviteePage.getByLabel(/^password$/i).fill('e2e-password-123')
+ await inviteePage.getByLabel(/confirm password/i).fill('e2e-password-123')
+ await inviteePage.getByRole('button', { name: /create account & accept/i }).click()
+
+ await expect(inviteePage).not.toHaveURL(/\/login/, { timeout: 15_000 })
+ await expect(inviteePage).not.toHaveURL(/\/accept-invitation/, { timeout: 15_000 })
+ } finally {
+ await inviteeContext.close()
+ }
+ })
+
+ test('shows an error for an invalid token', async ({ page }) => {
+ await page.goto('/accept-invitation/inv_doesnotexist?token=bogus-token-here')
+ await expect(page.getByText(/invitation not found/i)).toBeVisible({ timeout: 15_000 })
+ })
+})
diff --git a/packages/admin/e2e/paths.ts b/packages/admin/e2e/paths.ts
new file mode 100644
index 0000000000..4893832429
--- /dev/null
+++ b/packages/admin/e2e/paths.ts
@@ -0,0 +1,6 @@
+import { dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+export const E2E_DIR = dirname(fileURLToPath(import.meta.url))
+export const CREDENTIALS_FILE = resolve(E2E_DIR, '.credentials.json')
+export const RAILS_PID_FILE = resolve(E2E_DIR, '.rails.pid')
diff --git a/packages/admin/package.json b/packages/admin/package.json
index c380a1e5bf..3fcb242aeb 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -10,7 +10,10 @@
"lint": "biome check .",
"lint:fix": "biome check --fix .",
"format": "biome format --write .",
- "preview": "vite preview"
+ "preview": "vite preview",
+ "test:e2e": "playwright test",
+ "test:e2e:ui": "playwright test --ui",
+ "test:e2e:install": "playwright install chromium"
},
"dependencies": {
"@base-ui/react": "^1.4.1",
@@ -44,6 +47,7 @@
"zod": "^4.4.1"
},
"devDependencies": {
+ "@playwright/test": "^1.59.1",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/router-plugin": "^1.167.29",
"@types/node": "^25.6.0",
diff --git a/packages/admin/playwright.config.ts b/packages/admin/playwright.config.ts
new file mode 100644
index 0000000000..db97ed9864
--- /dev/null
+++ b/packages/admin/playwright.config.ts
@@ -0,0 +1,55 @@
+import { defineConfig, devices } from '@playwright/test'
+
+// Ports kept distinct from the dev defaults (Rails :3000, Vite :5173) so an
+// E2E run never clobbers a developer's running stack.
+const RAILS_PORT = process.env.E2E_RAILS_PORT || '3010'
+const VITE_PORT = process.env.E2E_VITE_PORT || '5174'
+
+export default defineConfig({
+ testDir: './e2e',
+ // Sequential — the global Rails server + SQLite test DB are shared, and the
+ // suite mutates server state (creating invitations, accepting them).
+ fullyParallel: false,
+ workers: 1,
+
+ reporter: process.env.CI ? 'github' : 'list',
+ retries: process.env.CI ? 2 : 0,
+ timeout: 30_000,
+ expect: { timeout: 10_000 },
+
+ use: {
+ baseURL: `http://localhost:${VITE_PORT}`,
+ trace: 'on-first-retry',
+ screenshot: 'only-on-failure',
+ video: 'retain-on-failure',
+ },
+
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+
+ // Boots Rails + the seed pipeline once before the suite starts, then Vite
+ // dev pointed at that Rails. Playwright handles process lifecycle and waits
+ // for both to respond to a probe before any spec runs.
+ globalSetup: './e2e/global-setup.ts',
+ globalTeardown: './e2e/global-teardown.ts',
+
+ webServer: [
+ {
+ // Vite dev — proxies `/api/*` to the test Rails per `vite.config.ts`,
+ // overridden via `VITE_SPREE_API_URL` so the proxy targets the test
+ // Rails port instead of the dev default.
+ command: `pnpm dev --port ${VITE_PORT}`,
+ url: `http://localhost:${VITE_PORT}`,
+ reuseExistingServer: false,
+ timeout: 60_000,
+ stdout: 'ignore',
+ stderr: 'pipe',
+ env: {
+ // Vite proxy target — the SDK keeps relative URLs so the SPA stays
+ // same-origin with the proxy, exactly like dev. Setting
+ // `VITE_SPREE_API_URL` here would flip the SDK to absolute URLs and
+ // break the cookie path the refresh flow depends on.
+ VITE_API_PROXY_TARGET: `http://localhost:${RAILS_PORT}`,
+ },
+ },
+ ],
+})
diff --git a/packages/admin/src/components/spree/top-bar.tsx b/packages/admin/src/components/spree/top-bar.tsx
index 890b2c1ff6..2abc7f2f42 100644
--- a/packages/admin/src/components/spree/top-bar.tsx
+++ b/packages/admin/src/components/spree/top-bar.tsx
@@ -114,6 +114,7 @@ function TopBarUser() {
<DropdownMenuTrigger asChild>
<button
type="button"
+ aria-label="User menu"
className="flex items-center gap-2 rounded-lg p-1 transition-colors hover:bg-accent"
>
<Avatar className="size-7">
diff --git a/packages/admin/src/providers/auth-provider.tsx b/packages/admin/src/providers/auth-provider.tsx
index 782ea08caf..3fb0ff8220 100644
--- a/packages/admin/src/providers/auth-provider.tsx
+++ b/packages/admin/src/providers/auth-provider.tsx
@@ -1,4 +1,4 @@
-import type { InvitationAcceptParams } from '@spree/admin-sdk'
+import type { AuthTokens, InvitationAcceptParams } from '@spree/admin-sdk'
import { createContext, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
import { adminClient } from '@/client'
@@ -13,17 +13,10 @@ interface AuthContextValue {
user: AuthUser | null
token: string | null
isAuthenticated: boolean
- /** True until the cold-load /auth/refresh bootstrap settles. */
isInitializing: boolean
- /** True while a login submission is in flight. */
isLoading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => Promise<void>
- /**
- * Drives the public invitation-acceptance flow. On success the issued JWT +
- * refresh-token cookie behave identically to a fresh login — the provider's
- * normal refresh loop takes over from there.
- */
acceptInvitation: (id: string, token: string, params: InvitationAcceptParams) => Promise<void>
}
@@ -89,11 +82,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, REFRESH_INTERVAL_MS)
}, [refreshAccessToken, clearRefreshTimer])
- const login = useCallback(
- async (email: string, password: string) => {
+ const establish = useCallback(
+ async (req: Promise<AuthTokens>) => {
setIsLoading(true)
try {
- const res = await adminClient.auth.login({ email, password })
+ const res = await req
applySession(res.token, res.user)
scheduleRefresh()
} finally {
@@ -103,18 +96,15 @@ export function AuthProvider({ children }: { children: ReactNode }) {
[applySession, scheduleRefresh],
)
+ const login = useCallback(
+ (email: string, password: string) => establish(adminClient.auth.login({ email, password })),
+ [establish],
+ )
+
const acceptInvitation = useCallback(
- async (id: string, token: string, params: InvitationAcceptParams) => {
- setIsLoading(true)
- try {
- const res = await adminClient.auth.acceptInvitation(id, token, params)
- applySession(res.token, res.user)
- scheduleRefresh()
- } finally {
- setIsLoading(false)
- }
- },
- [applySession, scheduleRefresh],
+ (id: string, token: string, params: InvitationAcceptParams) =>
+ establish(adminClient.auth.acceptInvitation(id, token, params)),
+ [establish],
)
const logout = useCallback(async () => {
diff --git a/packages/admin/src/routes/accept-invitation.$invitationId.tsx b/packages/admin/src/routes/accept-invitation.$invitationId.tsx
index 54f8ed5e69..6ceda31b28 100644
--- a/packages/admin/src/routes/accept-invitation.$invitationId.tsx
+++ b/packages/admin/src/routes/accept-invitation.$invitationId.tsx
@@ -148,8 +148,8 @@ function SignInForm({
</p>
)}
<div className="grid gap-2">
- <Label>Email</Label>
- <Input value={invitation.email} disabled />
+ <Label htmlFor="invitee-email">Email</Label>
+ <Input id="invitee-email" value={invitation.email} disabled />
</div>
<div className="grid gap-2">
<Label htmlFor="password">Password</Label>
@@ -227,8 +227,8 @@ function SignUpForm({
</p>
)}
<div className="grid gap-2">
- <Label>Email</Label>
- <Input value={invitation.email} disabled />
+ <Label htmlFor="invitee-email">Email</Label>
+ <Input id="invitee-email" value={invitation.email} disabled />
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
diff --git a/packages/admin/vite.config.ts b/packages/admin/vite.config.ts
index 9c4c431b6d..73ce709353 100644
--- a/packages/admin/vite.config.ts
+++ b/packages/admin/vite.config.ts
@@ -14,10 +14,18 @@ export default defineConfig({
// Proxy /api to the Rails server so the SPA is same-origin with the API in dev.
// Same-origin keeps the refresh-token cookie working under SameSite=Lax without
// needing HTTPS (production cross-origin uses SameSite=None; Secure).
+ //
+ // `VITE_API_PROXY_TARGET` is the proxy *target* — kept distinct from
+ // `VITE_SPREE_API_URL` (which the SDK reads at build time to switch to
+ // absolute URLs) so the E2E suite can keep dev's same-origin path even when
+ // pointing at a different Rails port.
server: {
proxy: {
'/api': {
- target: process.env.VITE_SPREE_API_URL || 'http://localhost:3000',
+ target:
+ process.env.VITE_API_PROXY_TARGET ||
+ process.env.VITE_SPREE_API_URL ||
+ 'http://localhost:3000',
changeOrigin: true,
},
},
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 357dfce68d..3f5688858f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -109,6 +109,9 @@ importers:
specifier: ^4.4.1
version: 4.4.1
devDependencies:
+ '@playwright/test':
+ specifier: ^1.59.1
+ version: 1.59.1
'@tailwindcss/vite':
specifier: ^4.2.4
@@ -924,6 +927,11 @@ packages:
'@oxc-project/[email protected]':
resolution: {integrity: sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ==}
+ '@playwright/[email protected]':
+ resolution: {integrity: sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==}
@@ -2436,6 +2444,11 @@ packages:
resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==}
engines: {node: '>=6 <7 || >=8'}
+ resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
+
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -3126,6 +3139,16 @@ packages:
resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}
+ resolution: {integrity: sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}
engines: {node: '>= 18'}
@@ -4632,6 +4655,10 @@ snapshots:
'@oxc-project/[email protected]': {}
+ '@playwright/[email protected]':
+ dependencies:
+ playwright: 1.59.1
+
'@radix-ui/[email protected]': {}
@@ -6021,6 +6048,9 @@ snapshots:
jsonfile: 4.0.0
universalify: 0.1.2
+ optional: true
+
optional: true
@@ -6584,6 +6614,14 @@ snapshots:
mlly: 1.8.0
pathe: 2.0.3
+
+ dependencies:
+ playwright-core: 1.59.1
+ optionalDependencies:
+ fsevents: 2.3.2
+
dependencies:
lilconfig: 3.1.3