Zum Inhalt springen
Skillpedia
Tests9.1k · #12310

writing-specs

Was er macht

Dieser Skill zeigt, wie du gut gegliederte Ginkgo-Tests in Go schreibst. Er richtet sich an Entwickler, die Ginkgo-Tests schreiben oder prüfen.

Wann du ihn nutzt

  • ✓Wenn du neue Ginkgo-Tests für ein Go-Paket schreibst.
  • ✓Wenn sich deine Ginkgo-Tests Daten teilen und sich gegenseitig stören.
  • ✓Wenn du vorhandenen Ginkgo-Testcode prüfen oder aufräumen willst.

Link zum Skill

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

Kopiere ihn und füge ihn in deine KI ein (Claude, ChatGPT oder Cursor) mit der Bitte, den Anweisungen zu folgen.

So nutzt du ihn

Am einfachsten: Kopiere die Nachricht und füge sie in deine KI ein. Sie liest den Skill und folgt den Anweisungen.

Fertige Nachricht zum Einfügen

Nutze diesen Skill, um mir zu helfen: https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/writing-specs/SKILL.md Lies die SKILL.md unter diesem Link und folge ihren Anweisungen für meine Aufgabe.
Soll deine KI Skills wie diesen selbst finden?Installiere den kostenlosen Skillpedia-MCP: eine Zeile, und sie durchsucht vor jeder Aufgabe 15.000+ Skills.In 1 Minute installieren →

Beispielanfrage an deine KI

“Schreib Ginkgo-Tests für meinen Go-Code zu einem Bücherregal, mit einem sauberen Setup für jeden Test.”

5 neue Skills pro Woche. 1 Minute Lesezeit.

So funktioniert es

Er erklärt die Teile eines Tests: Gruppen, die Tests ordnen, die Tests selbst und Setup-Code, der vor jedem Test frisch ausgeführt wird.

Technischer Inhalt (originale SKILL.md)

Originaltext des Autors, auf Englisch, direkt von 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

Häufige Fragen

Wo sollte ich Variablen für meine Tests ablegen?

Deklariere sie in der Gruppe und setze ihre Werte in einem Setup-Schritt, damit jeder Test sauber startet.

Was ist DeferCleanup?

Es plant einen Aufräumschritt nach einem Test ein, der auch dann läuft, wenn der Test fehlschlägt.

Kann ich Hilfsfunktionen für Tests schreiben?

Ja, der Skill behandelt wiederverwendbare Hilfsfunktionen, die Fehler in der richtigen Zeile melden.

Details

Originalbeschreibung des Autors

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

Beliebtheit

GitHub-Sterne
9.1k
Platz im Ranking
#12310
Lizenz
MIT
Aktualisiert
9.10.2026

Ist dieser Skill nützlich?

0

Anmelden um abzustimmen.

Kommentare

  • …

Weitere Skills aus diesem Repository

Ähnliche Skills