writing-specs
Qué hace
Esta skill muestra cómo escribir pruebas de Ginkgo bien organizadas en Go. Está pensada para desarrolladores que escriben o revisan pruebas en Go con Ginkgo.
Cuándo usarla
- ✓Cuando escribes pruebas nuevas de Ginkgo para un paquete de Go.
- ✓Cuando tus pruebas de Ginkgo comparten datos y empiezan a interferir entre sí.
- ✓Cuando quieres revisar u ordenar el código de pruebas de Ginkgo existente.
Link de la skill
https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/writing-specs/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Escribe pruebas de Ginkgo para mi código de estantería en Go, con una preparación limpia para cada prueba.”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
Explica las partes de una prueba: los grupos que organizan las pruebas, las propias pruebas y el código de preparación que se ejecuta de nuevo antes de cada una.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de 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 perIt. - The spec's full name is the concatenation of every container text plus the
Ittext — 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
BeforeEachso 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
})
DeferCleanupacceptsfunc(),func() error(a non-nil error fails the spec), captured arguments, and afunc(ctx SpecContext)form (→ginkgo:timeouts-and-async).- Restore original state; don't blindly clear it.
os.Unsetenvafter the test wrongly assumes the var started unset — capture and restore instead (as above). DeferCleanupis 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
Preguntas frecuentes
¿Dónde debo poner las variables de mis pruebas?
Decláralas en el grupo y asígnales valores en un paso de preparación, para que cada prueba empiece limpia.
¿Qué es DeferCleanup?
Programa un paso de limpieza que se ejecuta después de una prueba, incluso si la prueba falla.
¿Puedo crear funciones auxiliares para las pruebas?
Sí, la skill cubre funciones auxiliares reutilizables que informan de los fallos en la línea correcta.
Detalles
Descripción original del 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
Popularidad
- Estrellas en GitHub
- 9,1 mil
- Posición en el ranking
- #12310
- Licencia
- MIT
- Actualizada
- 9/10/2026
Comentarios
- …
Más skills de este repositorio
ci
9,1 milAyuda a tu agente a configurar pruebas de Ginkgo para la integración continua, con banderas recomendadas que detectan marcas de enfoque o pendientes olvidadas y pruebas inestables.
debugging-failures
9,1 milAyuda a tu agente a descubrir por qué fallaron las pruebas de Ginkgo, leyendo la línea de resumen y extrayendo de un informe JSON las pruebas y mensajes exactos que fallaron.
decorators
9,1 milAyuda a tu agente a usar bien los decoradores de pruebas de Ginkgo, como Serial, Ordered, Label, Focus y los tiempos límite, explicando qué hace cada uno.
filtering
9,1 milAyuda a tu agente a ejecutar solo algunas pruebas de Ginkgo, usando pending, skip, focus, etiquetas, restricciones de versión y filtros de archivo en el orden de prioridad correcto.
Skills parecidas
test-driven-development
311 milEnseña a tu agente a escribir primero una prueba que falle, verla fallar y después escribir el código más pequeño que la hace pasar, antes de construir cualquier función o corrección.
verification-before-completion
311 milEnseña a tu agente a ejecutar comprobaciones reales y leer su resultado antes de afirmar que una tarea, una corrección o una compilación está completa o en buen estado.
migrate-to-shoehorn
310 milSustituye los casts de tipo arriesgados de tus archivos de prueba por la librería shoehorn, para que las pruebas usen datos parciales y sigan pasando las comprobaciones de tipos.