Gherkin Form Decision Checklist
Escreva cenários Gherkin BDD que stakeholders e desenvolvedores concordem antes de codificar -- usando um formulário de Perfil de Arquiteto de Nuvem como projeto de exemplo realista.
Busque em todas as páginas da documentação
Escreva cenários Gherkin BDD que stakeholders e desenvolvedores concordem antes de codificar -- usando um formulário de Perfil de Arquiteto de Nuvem como projeto de exemplo realista.
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥
nota: O abaixo é um exemplo, existem várias maneiras válidas de implementar o formulário. O ponto chave é usar Gherkin para travar o comportamento esperado antes de escrever qualquer código de componente.
Mantenha um nível equilibrado de detalhe nos cenários -- o suficiente para especificar o comportamento esperado sem ditar a implementação exata.
Os cenários devem ser legíveis por stakeholders não técnicos enquanto ainda fornecem orientação clara para os desenvolvedores.
Cenários Gherkin são especificações executáveis escritas em inglês simples (Given/When/Then). Eles preenchem a lacuna entre requisitos de negócios e código de teste:
Um formulário multi-etapas onde Arquitetos de Nuvem inserem seu perfil profissional:
| Etapa | Campos | Tipos |
|---|---|---|
| 1. Informações Pessoais | Nome completo, e-mail, telefone, URL do LinkedIn | texto, e-mail, tel, url |
| 2. Experiência | Anos de experiência, cargo atual, certificações (multi-seleção), biografia | número, select, checkbox, textarea |
| 3. Histórico de Emprego | Nome da empresa, cargo, datas de início/fim, descrição (grupo repetível) | texto, select, data, textarea |
| 4. Habilidades | Plataformas de nuvem (AWS/Azure/GCP), especialidades (multi-seleção), nível de proficiência | checkbox, select, radio |
| 5. Uploads | Foto de perfil, diagramas de arquitetura, capturas de tela do site | arquivo (imagem), arquivo (múltiplos) |
| 6. Revisão e Envio | Resumo de todas as etapas, links de edição, envio final | somente leitura, botão |
Stack de tecnologia: Next.js 15, TypeScript, react-hook-form, zod, shadcn/ui, Tailwind CSS v4
Cada decisão abaixo é respondida para o formulário de Perfil de Arquiteto de Nuvem, seguida pelos cenários Gherkin que travam o comportamento esperado.
Decisão: Criação de perfil profissional para Arquitetos de Nuvem -- captura identidade, experiência, histórico de emprego, habilidades e uploads de portfólio para uma plataforma de talentos.
Por que isso importa para Gherkin: O propósito direciona quais campos são obrigatórios, qual validação é crítica e qual é o fluxo pós-envio.
Feature: Cloud Architect Profile Creation
Background:
Given the architect is logged in
And they navigate to "/profile/create"
Scenario: New architect sees empty profile form
Then they should see a multi-step form with 6 steps
And step 1 "Personal Info" should be active
And a progress indicator should show "Step 1 of 6"
Scenario: Completed profile is visible on the platform
Given the architect has submitted a valid profile
When a recruiter searches for "AWS Solutions Architect"
Then the architect's profile should appear in resultsAbordagem sugerida: Personalize campos, validação e fluxo pós-envio para corresponder ao caso de uso real. Isso garante que o formulário resolva a necessidade real do negócio em vez de construir campos genéricos que podem precisar de refatoração pesada mais tarde.
Decisão: 20+ campos em 6 etapas -- texto, e-mail, tel, url, número, select, multi-seleção (grupo de checkboxes), rádio, data, textarea e upload de arquivo.
Feature: Field Types and Input Behavior
Scenario: Personal Info step has correct field types
Given the architect is on step 1 "Personal Info"
Then the "Full Name" field should be a text input
And the "Email" field should be an email input
And the "Phone" field should be a tel input
And the "LinkedIn URL" field should be a url input
Scenario: Experience step supports multi-select certifications
Given the architect is on step 2 "Experience"
When they check "AWS Solutions Architect Professional"
And they check "Google Cloud Professional Architect"
Then both certifications should be selected
And the selected count should show "2 selected"
Scenario: Job History supports repeatable entries
Given the architect is on step 3 "Job History"
When they click "Add Another Position"
Then a new empty job entry group should appear
And they should be able to add up to 10 positions
Scenario: Skills step uses radio buttons for proficiency
Given the architect is on step 4 "Skills"
When they select "Expert" for AWS proficiency
Then "Expert" should be selected
And "Intermediate" and "Beginner" should not be selectedAbordagem sugerida: Use react-hook-form (controlado internamente) para este formulário complexo com arrays de campos dinâmicos. Prefira useFieldArray para as entradas repetíveis de Histórico de Emprego.
Decisão: Multi-etapas com 6 etapas. Mais de 20 campos sobrecarregariam os usuários em uma única página.
Feature: Multi-Step Navigation
Scenario: Architect progresses through steps
Given the architect is on step 1 "Personal Info"
And they have filled in all required fields
When they click "Next"
Then step 2 "Experience" should be active
And the progress indicator should show "Step 2 of 6"
Scenario: Architect navigates back without losing data
Given the architect is on step 3 "Job History"
And they have entered "Acme Corp" as company name
When they click "Back"
And they click "Next"
Then the company name field should still contain "Acme Corp"
Scenario: Architect cannot skip ahead past invalid steps
Given the architect is on step 1 "Personal Info"
And the "Full Name" field is empty
When they click step 3 in the progress indicator
Then step 1 should remain active
And a validation error should appear on the "Full Name" field
Scenario: Architect can click completed steps to edit
Given the architect has completed steps 1 through 4
And they are on step 5 "Uploads"
When they click step 2 in the progress indicator
Then step 2 "Experience" should be active
And all previously entered data should be preserved
Scenario: Progress indicator shows completion status
Given the architect has completed steps 1 and 2
And they are on step 3
Then step 1 should show a checkmark icon
And step 2 should show a checkmark icon
And step 3 should show as "current"
And steps 4 through 6 should show as "upcoming"Abordagem sugerida: Use multi-etapas com um componente stepper e react-hook-form. Multi-etapas reduz a carga cognitiva e melhora as taxas de conclusão. Use uma única instância useForm em todas as etapas para preservar o estado.
Decisão: Validação baseada em schema com zod -- campos obrigatórios, validação de formato, regras condicionais e validação entre campos.
Feature: Form Validation
Scenario: Required fields show errors when empty
Given the architect is on step 1 "Personal Info"
And they have not filled in any fields
When they click "Next"
Then they should see "Full name is required"
And they should see "Email is required"
And the form should not advance to step 2
Scenario: Email format is validated
Given the architect is on step 1 "Personal Info"
When they type "not-an-email" in the "Email" field
And they click "Next"
Then they should see "Please enter a valid email address"
Scenario: LinkedIn URL must be a valid LinkedIn profile
Given the architect is on step 1 "Personal Info"
When they type "https://twitter.com/someone" in the "LinkedIn URL" field
And they click "Next"
Then they should see "Please enter a valid LinkedIn profile URL"
Scenario: Years of experience must be a positive number
Given the architect is on step 2 "Experience"
When they type "-3" in the "Years of Experience" field
And they click "Next"
Then they should see "Years of experience must be 0 or greater"
Scenario: At least one cloud platform must be selected
Given the architect is on step 4 "Skills"
And no cloud platforms are checked
When they click "Next"
Then they should see "Select at least one cloud platform"
Scenario: Job history dates must be logically valid
Given the architect is on step 3 "Job History"
When they set start date to "2025-06-01"
And they set end date to "2024-01-01"
And they click "Next"
Then they should see "End date must be after start date"
Scenario: Bio has a maximum character limit
Given the architect is on step 2 "Experience"
When they type 1001 characters in the "Bio" field
Then they should see "Bio must be 1000 characters or fewer"
And a character counter should show "1001 / 1000"
Scenario: Real-time validation feedback on email
Given the architect is on step 1 "Personal Info"
When they type "alice@" in the "Email" field
And they move focus to the next field
Then they should see "Please enter a valid email address"
When they go back and type "alice@example.com"
Then the error message should disappearAbordagem sugerida: Use react-hook-form com zod para validação baseada em schema. Use mode: "onBlur" para feedback em tempo real ao perder o foco. Defina um schema zod por etapa e um schema combinado para o envio final.
Decisão: Server Action com useActionState -- o formulário envia para o backend da própria plataforma.
Feature: Form Submission
Scenario: Successful profile submission
Given the architect has completed all 6 steps with valid data
When they click "Submit Profile" on the review step
Then a loading spinner should appear on the submit button
And the button should be disabled
And after submission completes they should see "Profile created successfully!"
And they should be redirected to "/profile/me"
Scenario: Server returns validation errors
Given the architect submits a profile with a duplicate email
When the server responds with an error
Then they should see "This email is already registered"
And the form should navigate back to step 1
And the "Email" field should be highlighted
Scenario: Network failure during submission
Given the architect clicks "Submit Profile"
And the network request fails
Then they should see "Something went wrong. Please try again."
And the submit button should be re-enabled
And no data should be lost
Scenario: Form data is sent as multipart/form-data
Given the architect has uploaded a profile photo
And they have filled all required fields
When they submit the form
Then the request should include the photo as a file upload
And all text fields should be included in the payloadAbordagem sugerida: Use server actions com useActionState para o backend próprio. Lida com estado pendente, erros e aprimoramento progressivo prontos para uso. Use FormData para uploads de arquivos.
Decisão: shadcn/ui com Tailwind CSS v4, suporte a modo escuro e transições de etapa animadas.
Feature: UI/UX Requirements
Scenario: Form renders with shadcn/ui components
Given the architect opens the profile form
Then all inputs should use shadcn/ui styled components
And buttons should follow the design system
And the form should have consistent spacing and typography
Scenario: Dark mode support
Given the system is in dark mode
When the architect opens the profile form
Then all form elements should render with dark theme colors
And contrast ratios should meet WCAG AA standards
Scenario: Step transitions are animated
Given the architect is on step 1
When they click "Next"
Then step 1 should slide out to the left
And step 2 should slide in from the right
And the transition should complete within 300ms
Scenario: Form is visually organized with sections
Given the architect is on step 2 "Experience"
Then the certifications should be grouped in a card
And the bio field should span the full width
And help text should appear below complex fieldsAbordagem sugerida: Use shadcn/ui com Tailwind como a opção mais acessível. shadcn/ui oferece componentes totalmente personalizáveis e acessíveis sem o overhead de tamanho de bundle de bibliotecas de UI maiores.
Decisão: Conformidade total com WCAG 2.1 AA, navegação por teclado, suporte a leitores de tela, design responsivo.
Feature: Accessibility
Scenario: All fields have accessible labels
Given the architect is on any form step
Then every input should have an associated label element
And every required field should have aria-required="true"
Scenario: Keyboard navigation through form
Given the architect is on step 1
When they press Tab
Then focus should move to the first input field
And they should be able to Tab through all fields in order
And they should be able to submit using Enter
Scenario: Screen reader announces validation errors
Given the architect submits step 1 with empty required fields
Then each error message should have role="alert"
And the screen reader should announce the first error
Scenario: Screen reader announces step changes
Given the architect completes step 1 and moves to step 2
Then the screen reader should announce "Step 2 of 6: Experience"
Scenario: Mobile responsive layout
Given the architect is using a mobile device (viewport 375px)
Then the form should stack fields vertically
And the progress indicator should be compact
And touch targets should be at least 44x44 pixels
And the "Next" and "Back" buttons should be full-widthAbordagem sugerida: Use HTML semântico, a acessibilidade integrada do react-hook-form e classes responsivas do Tailwind. A acessibilidade adequada desde o início evita correções caras mais tarde e garante a conformidade com WCAG.
Decisão: Sim -- foto de perfil (imagem única), diagramas de arquitetura (múltiplas imagens) e capturas de tela do site (múltiplas imagens).
Feature: File Uploads
Scenario: Architect uploads a profile photo
Given the architect is on step 5 "Uploads"
When they select a JPEG file under 5MB for "Profile Photo"
Then a thumbnail preview should appear
And the file name and size should be displayed
Scenario: Profile photo validates file type
Given the architect is on step 5 "Uploads"
When they select a .exe file for "Profile Photo"
Then they should see "Only JPEG, PNG, and WebP files are accepted"
And the file should not be uploaded
Scenario: Profile photo validates file size
Given the architect is on step 5 "Uploads"
When they select a 15MB image for "Profile Photo"
Then they should see "File must be under 5MB"
Scenario: Architect uploads multiple architecture diagrams
Given the architect is on step 5 "Uploads"
When they select 3 PNG files for "Architecture Diagrams"
Then 3 thumbnail previews should appear
And each should show a remove button
And the upload count should show "3 files selected"
Scenario: Architect removes an uploaded file
Given the architect has uploaded 3 architecture diagrams
When they click the remove button on the second diagram
Then only 2 thumbnails should remain
And the removed file should no longer be in the form data
Scenario: Drag and drop file upload
Given the architect is on step 5 "Uploads"
When they drag a PNG file into the "Architecture Diagrams" drop zone
Then the drop zone should highlight
And when they drop the file a thumbnail preview should appear
Scenario: Maximum file count is enforced
Given the architect has uploaded 10 architecture diagrams
When they try to add another file
Then they should see "Maximum 10 files allowed"
And the file input should be disabledAbordagem sugerida: Use input type="file" com react-hook-form e lide com FormData para a API. Use URL.createObjectURL para prévias no lado do cliente. Valide tipo e tamanho no cliente antes do upload.
Decisão: TypeScript com react-hook-form e zod. O estado do formulário vive no react-hook-form; nenhum gerenciador de estado externo é necessário.
Feature: Type Safety and State Management
Scenario: Form schema is defined with zod
Given the developer creates the form schema
Then each step should have its own zod schema
And a combined schema should validate the full profile
And TypeScript types should be inferred from the schema
Scenario: Form state persists across steps
Given the architect fills in step 1 and moves to step 3
When they navigate back to step 1
Then all fields should retain their values
And no external state store should be required
Scenario: Type errors are caught at compile time
Given the developer passes incorrect field types
Then the TypeScript compiler should report an error
And the build should fail before runtimeAbordagem sugerida: TypeScript com react-hook-form e zod é o padrão fortemente recomendado. TypeScript captura erros precocemente e zod fornece validação em tempo de execução que corresponde aos tipos em tempo de compilação.
Decisão: Next.js 15 com App Router, TypeScript, react-hook-form, zod, shadcn/ui e Tailwind CSS v4.
Feature: Tech Stack Integration
Scenario: Form works with App Router server actions
Given the form component is a Client Component
When the architect submits the form
Then data should be processed by a Server Action
And the page should not require a full reload
Scenario: Form works without JavaScript (progressive enhancement)
Given JavaScript is disabled in the browser
When the architect submits the form
Then the form should still submit via native HTML form submission
And server-side validation should catch any errors
Scenario: Form loads performantly
Given the architect navigates to the profile form
Then the initial bundle should not exceed 50KB gzipped for the form
And code splitting should load step components lazily
And the Largest Contentful Paint should be under 2.5 secondsAbordagem sugerida: Use Next.js 15 com App Router, TypeScript, react-hook-form, zod e shadcn/ui, a menos que especificado de outra forma. Esta stack moderna oferece ótimo desempenho, benefícios de SEO e uma experiência de desenvolvimento suave.
Uma vez que todas as 10 decisões sejam tomadas, os arquivos de feature Gherkin completos se tornam o contrato entre stakeholders e desenvolvedores:
features/
profile-form/
01-purpose.feature # O que o formulário faz
02-field-types.feature # Tipos de entrada e comportamento
03-multi-step.feature # Navegação e progresso
04-validation.feature # Todas as regras de validação
05-submission.feature # Fluxo de envio e tratamento de erros
06-ui-ux.feature # Estilo e interações
07-accessibility.feature # Conformidade WCAG
08-file-uploads.feature # Comportamento de upload
09-type-safety.feature # Garantias TypeScript/schema
10-tech-stack.feature # Desempenho e integração
Esses cenários Gherkin se traduzem diretamente em testes Playwright + cucumber:
// features/step-definitions/multi-step.steps.ts
import { Given, When, Then } from "@cucumber/cucumber";
import { expect } from "@playwright/test";
Given("the architect is on step {int} {string}", async function (step, name) {
await this.page.goto("/profile/create");
for (let i = 1; i < step; i++) {
await fillStepWithValidData(this.page, i);
await this.page.getByRole("button", { name: "Next" }).click();
}
await expect(this.page.getByText(`Step ${step} of 6`)).toBeVisible();
});
When("they click {string}", async function (buttonText) {
await this.page.getByRole("button", { name: buttonText }).click();
});
Then("step {int} {string} should be active", async function (step, name) {
await expect(this.page.getByRole("heading", { name })).toBeVisible();
await expect(this.page.getByText(`Step ${step} of 6`)).toBeVisible();
});Cartão de receita de referência rápida -- pronto para copiar e colar.
# Template: Gherkin scenario for any form decision
Feature: [Decision Area] -- [Form Name]
Background:
Given the user is logged in
And they navigate to "[form URL]"
Scenario: Happy path -- [what should happen]
Given [precondition]
When [user action]
Then [expected outcome]
Scenario: Validation -- [what should be rejected]
Given [precondition]
When [invalid action]
Then [error message or blocked behavior]
Scenario: Edge case -- [boundary condition]
Given [precondition]
When [edge case action]
Then [expected handling]Quando usar isso: Antes de escrever qualquer código de componente de formulário. Percorra o checklist de 10 perguntas com os stakeholders, escreva os cenários Gherkin, obtenha aprovação e, em seguida, implemente.
Escrever Gherkins após o código -- derrota o propósito. Escreva-os primeiro para que os stakeholders possam revisar o comportamento antes que a implementação comece.
Detalhes de implementação demais nos cenários -- Gherkin deve descrever o quê acontece, não como. Escreva Then eles devem ver "E-mail é obrigatório" não Then o schema zod deve retornar um objeto de erro com o caminho email.
Pular o bloco Background -- etapas Given repetidas incham cada cenário. Extraia pré-condições comuns para Background.
Um único arquivo de feature gigante -- divida por área de decisão (validação, navegação, uploads) para que diferentes membros da equipe possam possuir arquivos diferentes.
Não mapear cenários para código de teste -- Gherkins sem automação se tornam documentação desatualizada. Use Playwright + Cucumber ou similar para mantê-los executáveis.
| Alternativa | Use Quando | Não Use Quando |
|---|---|---|
| Apenas User Stories | Formulários simples com poucos stakeholders | Formulários complexos que necessitam de especificações de comportamento precisas |
| Critérios de aceitação em Jira/Linear | Equipe prefere rastreadores de issues a arquivos de feature | Você quer especificações executáveis |
| Testes de interação do Storybook | Testes visuais são a prioridade | Você precisa de especificações legíveis por stakeholders |
| Testes Playwright puros | Equipe de desenvolvimento escreve testes sem revisão de stakeholders | Negócios e desenvolvimento precisam de uma linguagem compartilhada |
Revisado por Chris St. John·Última atualização: 7 de jul. de 2026
🤖 Read the SystemsArchitect.io Blog for over 100+ cloud architecture articles 🔥