The Core DSL provides the fundamental building blocks for writing Ginkgo specs, including container nodes for organization, subject nodes for tests, and lifecycle hooks for setup and teardown.
Runs the test suite. Must be called from a go test function.
func RunSpecs(t GinkgoTestingT, description string, args ...any) boolParameters:
t: Testing interface (typically *testing.T)description: Suite descriptionargs: Optional decorators (Label, etc.)Returns: true if suite passed, false otherwise
Example:
func TestBooks(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Books Suite", Label("integration"))
}Generates a preview of specs without running them. Useful for understanding test structure.
func PreviewSpecs(description string, args ...any) ReportParameters:
description: Suite descriptionargs: Optional decoratorsReturns: Report containing all spec reports that would run
Runs once before any specs execute. Used for expensive suite-wide setup.
func BeforeSuite(body any, args ...any) boolParameters:
body: Function to execute (can accept SpecContext or no arguments)args: Optional decorators (NodeTimeout, Label, etc.)Example:
var dbConnection *sql.DB
BeforeSuite(func() {
var err error
dbConnection, err = sql.Open("postgres", "...")
Expect(err).NotTo(HaveOccurred())
}, NodeTimeout(10*time.Second))Runs once after all specs complete. Used for suite-wide cleanup.
func AfterSuite(body any, args ...any) boolParameters:
body: Function to execute (can accept SpecContext or no arguments)args: Optional decoratorsExample:
AfterSuite(func() {
if dbConnection != nil {
dbConnection.Close()
}
})Coordinates suite setup across parallel processes. The first function runs on process 1 only, then its return value is passed to the second function which runs on all processes.
func SynchronizedBeforeSuite(
process1Body any,
allProcessesBody any,
args ...any,
) boolParameters:
process1Body: Function that runs only on process 1, returns data to shareallProcessesBody: Function that runs on all processes, receives shared dataargs: Optional decoratorsExample:
var sharedConfig []byte
SynchronizedBeforeSuite(func() []byte {
// Runs only on process 1
config := generateExpensiveConfig()
return config
}, func(data []byte) {
// Runs on all processes
sharedConfig = data
})Coordinates suite cleanup across parallel processes. The first function runs on all processes, then the second runs only on process 1.
func SynchronizedAfterSuite(
allProcessesBody any,
process1Body any,
args ...any,
) boolParameters:
allProcessesBody: Function that runs on all processesprocess1Body: Function that runs only on process 1args: Optional decoratorsExample:
SynchronizedAfterSuite(func() {
// Cleanup on each process
closeLocalResources()
}, func() {
// Cleanup shared resources on process 1
cleanupSharedInfrastructure()
})Container nodes organize specs into hierarchical groups.
Creates a container node for grouping related specs.
func Describe(text string, args ...any) boolParameters:
text: Description of the containerargs: Child nodes and decoratorsExample:
Describe("Book", func() {
It("has a title", func() {
// test code
})
Context("when saving", func() {
It("persists to database", func() {
// test code
})
})
})Focused Describe - only specs in focused containers run.
func FDescribe(text string, args ...any) boolPending Describe - marks all specs in container as pending.
func PDescribe(text string, args ...any) boolAlias for PDescribe - marks specs within the Describe block as pending.
var XDescribe = PDescribeAlias for Describe. Use to express different contexts or states.
var Context = Describe
var FContext = FDescribe
var PContext = PDescribe
var XContext = XDescribe // Alias for PDescribe, which equals PContextExpresses conditional scenarios. Similar to Describe but prepends "when " to the text.
func When(text string, args ...any) bool
func FWhen(text string, args ...any) bool
func PWhen(text string, args ...any) bool
var XWhen = PWhen // Alias for PWhenNote: When, FWhen, and PWhen automatically prepend "when " to the provided text.
Example:
Describe("Calculator", func() {
Context("with positive numbers", func() {
When("adding", func() {
It("returns sum", func() {
// test code
})
})
})
})Subject nodes define individual test cases.
Defines a single spec (test case).
func It(text string, args ...any) boolParameters:
text: Description of what the spec testsargs: Test body function and optional decoratorsExample:
It("validates email addresses", func() {
valid := ValidateEmail("test@example.com")
Expect(valid).To(BeTrue())
})
It("handles timeouts", func(ctx SpecContext) {
// Use ctx for cancellation-aware operations
Eventually(ctx, longRunningOperation).Should(Succeed())
}, SpecTimeout(5*time.Second))Focused It - only focused specs run.
func FIt(text string, args ...any) boolPending It - marks spec as pending (not run).
func PIt(text string, args ...any) boolAlias for PIt.
var XIt = PItAlias for It. Use when "It" doesn't read naturally.
var Specify = It
var FSpecify = FIt
var PSpecify = PIt
var XSpecify = XItExample:
Specify("the system should handle edge cases", func() {
// test code
})Runs before each spec in the container.
func BeforeEach(args ...any) boolParameters:
args: Setup function and optional decoratorsExample:
var book *Book
BeforeEach(func() {
book = &Book{Title: "Test Book"}
})
It("has a title", func() {
Expect(book.Title).To(Equal("Test Book"))
})Runs after each spec in the container.
func AfterEach(args ...any) boolExample:
var tempFile string
BeforeEach(func() {
tempFile = createTempFile()
})
AfterEach(func() {
os.Remove(tempFile)
})Runs after all BeforeEach blocks but immediately before the It block.
func JustBeforeEach(args ...any) boolExample:
var book *Book
var result error
BeforeEach(func() {
book = &Book{}
})
JustBeforeEach(func() {
// Runs after all BeforeEach blocks
result = book.Validate()
})
Context("with valid data", func() {
BeforeEach(func() {
book.Title = "Valid Title"
})
It("validates successfully", func() {
Expect(result).To(Succeed())
})
})Runs immediately after the It block but before AfterEach blocks.
func JustAfterEach(args ...any) boolExample:
JustAfterEach(func() {
// Captures state right after test
if CurrentSpecReport().Failed() {
captureDebugInfo()
}
})Runs once before all specs in an Ordered container.
func BeforeAll(args ...any) boolExample:
Describe("Sequential operations", Ordered, func() {
var database *DB
BeforeAll(func() {
database = setupDatabase()
})
It("creates record", func() {
database.Create(record)
})
It("reads record", func() {
database.Read(record.ID)
})
AfterAll(func() {
database.Close()
})
})Runs once after all specs in an Ordered container.
func AfterAll(args ...any) boolRegisters a cleanup function to run at the appropriate time. Cleanup functions run in LIFO order.
func DeferCleanup(args ...any)Parameters:
args: Cleanup function and its argumentsExample:
BeforeEach(func() {
file, err := os.Create("temp.txt")
Expect(err).NotTo(HaveOccurred())
DeferCleanup(os.Remove, "temp.txt")
conn, err := sql.Open("postgres", "...")
Expect(err).NotTo(HaveOccurred())
DeferCleanup(conn.Close)
})Marks the current spec as failed with a message.
func Fail(message string, callerSkip ...int)Parameters:
message: Failure messagecallerSkip: Optional number of stack frames to skip for reportingExample:
It("handles failures", func() {
if !isValid() {
Fail("Validation failed")
}
})Fails the current spec and skips all subsequent specs.
func AbortSuite(message string, callerSkip ...int)Example:
BeforeSuite(func() {
if !canConnectToDatabase() {
AbortSuite("Cannot connect to database")
}
})Skips the current spec with a message.
func Skip(message string, callerSkip ...int)Example:
It("requires linux", func() {
if runtime.GOOS != "linux" {
Skip("Only runs on Linux")
}
// test code
})Recovers from panics in goroutines. Should be deferred in goroutines spawned by specs.
func GinkgoRecover()Example:
It("handles panics in goroutines", func() {
done := make(chan bool)
go func() {
defer GinkgoRecover()
defer close(done)
// Code that might panic
riskyOperation()
}()
Eventually(done).Should(BeClosed())
})Returns the current suite and reporter configuration.
func GinkgoConfiguration() (SuiteConfig, ReporterConfig)Example:
suiteConfig, reporterConfig := GinkgoConfiguration()
fmt.Printf("Random seed: %d\n", suiteConfig.RandomSeed)Returns the random seed used for spec randomization.
func GinkgoRandomSeed() int64Returns the current parallel process number (1-indexed).
func GinkgoParallelProcess() intExample:
BeforeEach(func() {
// Use different test data per process
processNum := GinkgoParallelProcess()
testData = loadTestData(processNum)
})Returns the configured label filter expression.
func GinkgoLabelFilter() stringReturns the configured semantic version filter.
func GinkgoSemVerFilter() stringMarks the calling function as a helper. Failures in helper functions report the caller's location.
func GinkgoHelper()Example:
func ExpectValidEmail(email string) {
GinkgoHelper()
Expect(ValidateEmail(email)).To(BeTrue(),
"Expected %s to be valid email", email)
}
It("validates emails", func() {
ExpectValidEmail("test@example.com") // Failure reports this line
})Writer for test output. Content is captured and only displayed for failed specs (or when running in verbose mode).
type GinkgoWriterInterface interface {
io.Writer
Print(a ...any)
Printf(format string, a ...any)
Println(a ...any)
TeeTo(writer io.Writer)
ClearTeeWriters()
}
var GinkgoWriter GinkgoWriterInterfaceExample:
It("logs debug info", func() {
GinkgoWriter.Println("Starting test")
result := performOperation()
GinkgoWriter.Printf("Result: %v\n", result)
Expect(result).To(BeTrue())
})Logr-compatible logger that writes to GinkgoWriter.
var GinkgoLogr logr.LoggerExample:
It("uses structured logging", func() {
logger := GinkgoLogr.WithName("test")
logger.Info("operation started", "id", 123)
// Perform operation
logger.Info("operation completed")
})Returns a testing.T-compatible interface for the current spec.
func GinkgoT(optionalOffset ...int) FullGinkgoTInterface
type FullGinkgoTInterface interface {
GinkgoTInterface
// Report entry methods
AddReportEntryVisibilityAlways(name string, args ...any)
AddReportEntryVisibilityFailureOrVerbose(name string, args ...any)
AddReportEntryVisibilityNever(name string, args ...any)
// Print to GinkgoWriter
Print(a ...any)
Printf(format string, a ...any)
Println(a ...any)
// Color formatting
F(format string, args ...any) string
Fi(indentation uint, format string, args ...any) string
Fiw(indentation uint, maxWidth uint, format string, args ...any) string
// Timeline and recovery
RenderTimeline() string
GinkgoRecover()
DeferCleanup(args ...any)
// Configuration access
RandomSeed() int64
ParallelProcess() int
ParallelTotal() int
// Progress reporting
AttachProgressReporter(func() string) func()
}Example:
It("works with testing.T APIs", func() {
t := GinkgoT()
t.Log("This is a log message")
tempDir := t.TempDir()
// Use tempDir for temporary files
})Returns a testing.TB-compatible wrapper.
func GinkgoTB(optionalOffset ...int) *GinkgoTBWrapper
type GinkgoTBWrapper interface {
Cleanup(func())
Error(args ...any)
Errorf(format string, args ...any)
Fail()
FailNow()
Failed() bool
Fatal(args ...any)
Fatalf(format string, args ...any)
Helper()
Log(args ...any)
Logf(format string, args ...any)
Name() string
Setenv(key, value string)
Skip(args ...any)
SkipNow()
Skipf(format string, args ...any)
Skipped() bool
TempDir() string
}Temporarily pauses output interception.
func PauseOutputInterception()Resumes output interception after pausing.
func ResumeOutputInterception()Example:
It("shows immediate output", func() {
PauseOutputInterception()
fmt.Println("This prints immediately")
ResumeOutputInterception()
fmt.Println("This is captured")
})Registers a progress reporter callback that's invoked when progress is emitted.
func AttachProgressReporter(reporter func() string) func()Parameters:
reporter: Function that returns progress information as a stringReturns: Function to detach the progress reporter
Example:
BeforeEach(func() {
detach := AttachProgressReporter(func() string {
return fmt.Sprintf("Current operation: %s", getCurrentOp())
})
DeferCleanup(detach)
})Documents steps within a spec. Useful for understanding spec flow and debugging.
func By(text string, callback ...func())Parameters:
text: Step descriptioncallback: Optional function to execute for this stepExample:
It("performs multi-step operation", func() {
By("creating the resource")
resource := CreateResource()
By("validating the resource")
Expect(resource.Validate()).To(Succeed())
By("saving the resource", func() {
err := resource.Save()
Expect(err).NotTo(HaveOccurred())
})
})Minimal testing interface required by RunSpecs.
type GinkgoTestingT interface {
Fail()
}Context interface for interruptible specs. Extends context.Context.
type SpecContext interface {
context.Context
}Example:
It("respects context cancellation", func(ctx SpecContext) {
result := make(chan string, 1)
go func() {
select {
case <-ctx.Done():
return
case <-time.After(10 * time.Second):
result <- "completed"
}
}()
Eventually(ctx, result).Should(Receive(Equal("completed")))
}, SpecTimeout(15*time.Second))Deprecated: Use GinkgoParallelProcess instead.
func GinkgoParallelNode() intDeprecated: Removed in Ginkgo 2.0. Use the gmeasure package instead.
func Measure(_ ...any) boolDeprecated: Use CurrentSpecReport instead.
func CurrentGinkgoTestDescription() DeprecatedGinkgoTestDescriptionReturns information about the currently running test. Replaced by CurrentSpecReport() which provides a more comprehensive SpecReport type.
Deprecated: Custom reporters removed in Ginkgo 2.0.
func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, _ []Reporter) boolThis function simply calls RunSpecs(). Use Ginkgo's reporting nodes and 2.0 reporting infrastructure instead.
Deprecated: Custom reporters removed in Ginkgo 2.0.
func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, _ []Reporter) boolThis function simply calls RunSpecs(). Use Ginkgo's reporting nodes and 2.0 reporting infrastructure instead.
Deprecated: Use SpecReport instead.
type DeprecatedGinkgoTestDescription struct {
FullTestText string
ComponentTexts []string
TestText string
FileName string
LineNumber int
Failed bool
Duration time.Duration
}Replaced by the more comprehensive SpecReport type. Use CurrentSpecReport() instead of CurrentGinkgoTestDescription().
Deprecated alias for DeprecatedGinkgoTestDescription.
type GinkgoTestDescription = DeprecatedGinkgoTestDescriptionDeprecated: Removed in Ginkgo 2.0.
type Benchmarker interface {
Time(name string, body func(), info ...any) (elapsedTime time.Duration)
RecordValue(name string, value float64, info ...any)
RecordValueWithPrecision(name string, value float64, units string, precision int, info ...any)
}Use Gomega's gmeasure package instead for benchmarking.
Deprecated: Done channel pattern no longer supported.
type Done = internal.DoneThe Done channel pattern for asynchronous testing is no longer supported in Ginkgo 2.0. Use interruptible node functions with SpecContext or context.Context parameters instead.
Interface matching testing.T methods.
type GinkgoTInterface interface {
Cleanup(func())
Chdir(dir string)
Context() context.Context
Setenv(kev, value string)
Error(args ...any)
Errorf(format string, args ...any)
Fail()
FailNow()
Failed() bool
Fatal(args ...any)
Fatalf(format string, args ...any)
Helper()
Log(args ...any)
Logf(format string, args ...any)
Name() string
Parallel()
Skip(args ...any)
SkipNow()
Skipf(format string, args ...any)
Skipped() bool
TempDir() string
Attr(key, value string)
Output() io.Writer
}The portion of the interface returned by GinkgoT() that maps onto methods in the testing package's T.