Pular para o conteúdo
Skillpedia
Testes9,1 mil · #12310

writing-specs

O que ela faz

Esta skill mostra como escrever testes Ginkgo bem organizados em Go. É para desenvolvedores que escrevem ou revisam testes em Go com Ginkgo.

Quando usar

  • ✓Quando você escreve novos testes Ginkgo para um pacote Go.
  • ✓Quando seus testes Ginkgo compartilham dados e começam a interferir uns nos outros.
  • ✓Quando quer revisar ou organizar código de testes Ginkgo existente.

Link da skill

https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/writing-specs/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/writing-specs/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Escreva testes Ginkgo para o meu código de estante de livros em Go, com uma preparação limpa para cada teste.”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

Explica as partes de um teste: grupos que organizam os testes, os próprios testes e o código de preparação que roda do zero antes de cada um.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

Writing Ginkgo specs

Assumes Ginkgo is wired into the suite (ginkgo:setup) and you know the two-phase model (ginkgo:overview). Docs: https://onsi.github.io/ginkgo/#writing-specs.

The shape of a spec

var _ = Describe("Books", func() {
	var book *books.Book          // declare here...

	BeforeEach(func() {
		book = &books.Book{        // ...initialize here, fresh per spec
			Title:  "Les Miserables",
			Author: "Victor Hugo",
			Pages:  2783,
		}
		Expect(book.IsValid()).To(BeTrue()) // assertions in setup are fine
	})

	Describe("categorizing", func() {
		Context("with more than 300 pages", func() {
			It("is a novel", func() {
				Expect(book.Category()).To(Equal(books.CategoryNovel))
			})
		})
	})
})
  • Containers (Describe/Context/When) organize; they're identical — pick the one that reads as a sentence. Subjects (It/Specify) hold the assertions; one spec runs per It.
  • The spec's full name is the concatenation of every container text plus the It text — write them to read as a phrase.

The rule that prevents most bugs: declare in container, initialize in setup

Container bodies run once, at tree-construction time (ginkgo:overview). So:

  • Declare shared variables in the container body (var book *books.Book).
  • Initialize them in BeforeEach so each spec gets a clean copy.
// WRONG — runs once at construction; every spec shares & pollutes one book
var _ = Describe("Books", func() {
	book := &books.Book{Pages: 2783}   // initialized at construction time
	It("mutates", func() { book.Pages = 0 })
	It("expects 2783", func() { Expect(book.Pages).To(Equal(2783)) }) // flaky under randomization
})

The same trap explains: no assertions in container bodies (they fire at construction, with no spec active) and no expensive/stateful work in container bodies. If you see logic directly inside a Describe/Context/When body, it almost always belongs in a BeforeEach.

Setup and cleanup nodes — and their ordering

Node Runs
BeforeEach Before each spec, outer→inner. The workhorse.
JustBeforeEach After all BeforeEaches, just before the It.
JustAfterEach Just after the It, before any AfterEach.
AfterEach After each spec, inner→outer (reverse).
BeforeSuite/AfterSuite Once, around the whole suite (top-level only).
BeforeAll/AfterAll Once per Ordered container (→ ginkgo:ordering-and-flakes).

JustBeforeEach separates creation from configuration. Let nested BeforeEaches configure inputs into declared variables, and do the single creation step in JustBeforeEach — so each context overrides just the inputs it cares about:

var jsonString string
BeforeEach(func() { jsonString = `{"id":1,"name":"Sally"}` })      // base config
JustBeforeEach(func() { user, err = NewUser(jsonString) })          // creation, runs last
Context("with malformed JSON", func() {
	BeforeEach(func() { jsonString = `{"oops"` })                  // override one input
	It("errors", func() { Expect(err).To(HaveOccurred()) })
})

Use it deliberately — deeply nested JustBeforeEaches get hard to follow.

Cleanup: prefer DeferCleanup, and restore rather than clear

DeferCleanup registers teardown next to the setup that needs it, and runs in LIFO order (like defer). It works in any setup/subject node and adapts to scope (called in BeforeSuite, it cleans up after the suite; in BeforeEach, after the spec):

BeforeEach(func() {
	original := os.Getenv("MODE")
	os.Setenv("MODE", "test")
	DeferCleanup(os.Setenv, "MODE", original) // captured args passed at cleanup time
})
  • DeferCleanup accepts func(), func() error (a non-nil error fails the spec), captured arguments, and a func(ctx SpecContext) form (→ ginkgo:timeouts-and-async).
  • Restore original state; don't blindly clear it. os.Unsetenv after the test wrongly assumes the var started unset — capture and restore instead (as above).
  • DeferCleanup is a function call, not a node — it's the one cleanup mechanism you may use inside setup/subject closures. You may not define nodes (It, BeforeEach, …) inside a running closure.

Capturing failure state: DeferOnFailure

DeferOnFailure registers diagnostics that run only if the spec fails, as soon as the failing node returns and before any teardown nodes — so they see the state that AfterEach/DeferCleanup are about t

Perguntas frequentes

Onde devo colocar as variáveis dos meus testes?

Declare-as no grupo e defina os valores em uma etapa de preparação, para que cada teste comece limpo.

O que é o DeferCleanup?

Ele agenda uma etapa de limpeza que roda depois de um teste, mesmo se o teste falhar.

Posso criar funções auxiliares para os testes?

Sim. A skill cobre funções auxiliares reutilizáveis que reportam as falhas na linha certa.

Detalhes

Descrição original do autor

Author good Ginkgo specs — container nodes (Describe/Context/When), subject nodes (It/Specify), setup/cleanup nodes (BeforeEach, JustBeforeEach, AfterEach, DeferCleanup, BeforeSuite/AfterSuite), capturing failure diagnostics before teardown with DeferOnFailure, the "declare in container, initialize in BeforeEach" rule, separating creation from configuration, reusable test helpers with GinkgoHelper()/GinkgoHelperGo(), and By/GinkgoWriter output. Use when writing or reviewing specs or extracting a test helper. Covers the tree-construction-time pitfalls (no assertions/init/loop-capture in contain

repo: onsi/ginkgo

Popularidade

Estrelas no GitHub
9,1 mil
Posição no ranking
#12310
Licença
MIT
Atualizada em
09/10/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas