Aller au contenu
Skillpedia
Tests9.1k · #12310

writing-specs

Ce qu’il fait

Ce skill montre comment écrire des tests Ginkgo bien organisés en Go. Il s'adresse aux développeurs qui écrivent ou relisent des tests Go avec Ginkgo.

Quand l’utiliser

  • ✓Quand vous écrivez de nouveaux tests Ginkgo pour un paquet Go.
  • ✓Lorsque vos tests Ginkgo partagent des données et commencent à interférer entre eux.
  • ✓Quand vous voulez relire ou nettoyer du code de test Ginkgo existant.

Lien du skill

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

Copiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.

Comment l’utiliser

Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.

Message prêt à coller

Utilise ce skill pour m’aider : https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/writing-specs/SKILL.md Lis le fichier SKILL.md de ce lien et suis ses instructions pour ma tâche.
Envie que votre IA trouve seule des skills comme celui-ci ?Installez le MCP gratuit de Skillpedia : une ligne, et elle cherche parmi 15 000+ skills avant chaque tâche.Installer en 1 minute →

Exemple de demande à votre IA

“Écris des tests Ginkgo pour mon code de bibliothèque en Go, avec une préparation propre pour chaque test.”

5 nouveaux skills par semaine. 1 minute de lecture.

Comment ça marche

Le skill explique les parties d'un test : les groupes qui organisent les tests, les tests eux-mêmes et le code de préparation qui s'exécute à neuf avant chacun.

Contenu technique (SKILL.md original)

Texte original de l’auteur, en anglais, directement depuis 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

Questions fréquentes

Où dois-je déclarer mes variables de test ?

Déclarez-les dans le groupe et attribuez-leur leurs valeurs lors d'une étape de préparation, afin que chaque test démarre proprement.

Qu'est-ce que DeferCleanup ?

C'est une étape de nettoyage programmée qui s'exécute après un test, même si celui-ci échoue.

Puis-je créer des fonctions d'aide pour les tests ?

Oui, le skill couvre les fonctions d'aide réutilisables qui signalent les échecs à la bonne ligne.

Détails

Description originale de l’auteur

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

Popularité

Étoiles GitHub
9.1k
Position au classement
#12310
Licence
MIT
Mis à jour
09/10/2026

Ce skill vous est-il utile ?

0

Connectez-vous pour voter.

Commentaires

  • …

Autres skills de ce dépôt

Skills similaires