Langsung ke konten
Skillpedia
Testing9.1k · #12310

writing-specs

Fungsinya

Skill ini menunjukkan cara menulis tes Ginkgo di Go yang terorganisasi dengan baik. Skill ini ditujukan untuk pengembang yang menulis atau meninjau tes Go dengan Ginkgo.

Kapan dipakai

  • ✓Saat Anda menulis tes Ginkgo baru untuk paket Go.
  • ✓Saat tes Ginkgo Anda berbagi data dan mulai saling mengganggu.
  • ✓Saat Anda ingin meninjau atau merapikan kode tes Ginkgo yang sudah ada.

Link skill

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

Salin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.

Cara pakai

Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.

Pesan siap tempel

Gunakan skill ini untuk membantu saya: https://github.com/onsi/ginkgo/blob/master/plugins/ginkgo/skills/writing-specs/SKILL.md Baca file SKILL.md di link tersebut dan ikuti instruksinya untuk tugas saya.
Mau AI Anda menemukan skill seperti ini sendiri?Pasang MCP Skillpedia gratis: cukup satu baris, dan AI mencari di antara 15.000+ skill sebelum tiap tugas.Pasang dalam 1 menit →

Contoh permintaan ke AI

“Tulis tes Ginkgo untuk kode rak buku Go saya, dengan persiapan yang bersih untuk setiap tes.”

5 skill baru setiap minggu. 1 menit baca.

Cara kerjanya

Skill menjelaskan bagian-bagian tes: grup yang mengatur tes, tes itu sendiri, dan kode persiapan yang berjalan baru sebelum setiap tes.

Konten teknis (SKILL.md asli)

Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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

Pertanyaan umum

Di mana sebaiknya saya meletakkan variabel untuk tes?

Deklarasikan di dalam grup dan isi nilainya pada langkah persiapan agar setiap tes mulai dengan bersih.

Apa itu DeferCleanup?

Itu menjadwalkan langkah pembersihan yang berjalan setelah tes, bahkan jika tes gagal.

Bisakah saya membuat fungsi bantu untuk tes?

Bisa. Skill membahas fungsi bantu yang dapat dipakai ulang dan melaporkan kegagalan pada baris yang tepat.

Detail

Deskripsi asli dari pembuat

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

Popularitas

Bintang GitHub
9.1k
Peringkat
#12310
Lisensi
MIT
Diperbarui
9/10/2026

Apakah skill ini berguna?

0

Masuk untuk memberi suara.

Komentar

  • …

Skill lain dari repositori ini

Skill serupa