or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdcore-dsl.mddecorators.mdextensions.mdindex.mdreporters.mdreporting.mdtable-driven-testing.mdtypes.md
tile.json

core-dsl.mddocs/

Core DSL

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.

Suite Lifecycle

RunSpecs

Runs the test suite. Must be called from a go test function.

func RunSpecs(t GinkgoTestingT, description string, args ...any) bool

Parameters:

  • t: Testing interface (typically *testing.T)
  • description: Suite description
  • args: 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"))
}

PreviewSpecs

Generates a preview of specs without running them. Useful for understanding test structure.

func PreviewSpecs(description string, args ...any) Report

Parameters:

  • description: Suite description
  • args: Optional decorators

Returns: Report containing all spec reports that would run

BeforeSuite

Runs once before any specs execute. Used for expensive suite-wide setup.

func BeforeSuite(body any, args ...any) bool

Parameters:

  • 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))

AfterSuite

Runs once after all specs complete. Used for suite-wide cleanup.

func AfterSuite(body any, args ...any) bool

Parameters:

  • body: Function to execute (can accept SpecContext or no arguments)
  • args: Optional decorators

Example:

AfterSuite(func() {
    if dbConnection != nil {
        dbConnection.Close()
    }
})

SynchronizedBeforeSuite

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,
) bool

Parameters:

  • process1Body: Function that runs only on process 1, returns data to share
  • allProcessesBody: Function that runs on all processes, receives shared data
  • args: Optional decorators

Example:

var sharedConfig []byte

SynchronizedBeforeSuite(func() []byte {
    // Runs only on process 1
    config := generateExpensiveConfig()
    return config
}, func(data []byte) {
    // Runs on all processes
    sharedConfig = data
})

SynchronizedAfterSuite

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,
) bool

Parameters:

  • allProcessesBody: Function that runs on all processes
  • process1Body: Function that runs only on process 1
  • args: Optional decorators

Example:

SynchronizedAfterSuite(func() {
    // Cleanup on each process
    closeLocalResources()
}, func() {
    // Cleanup shared resources on process 1
    cleanupSharedInfrastructure()
})

Container Nodes

Container nodes organize specs into hierarchical groups.

Describe

Creates a container node for grouping related specs.

func Describe(text string, args ...any) bool

Parameters:

  • text: Description of the container
  • args: Child nodes and decorators

Example:

Describe("Book", func() {
    It("has a title", func() {
        // test code
    })

    Context("when saving", func() {
        It("persists to database", func() {
            // test code
        })
    })
})

FDescribe

Focused Describe - only specs in focused containers run.

func FDescribe(text string, args ...any) bool

PDescribe

Pending Describe - marks all specs in container as pending.

func PDescribe(text string, args ...any) bool

XDescribe

Alias for PDescribe - marks specs within the Describe block as pending.

var XDescribe = PDescribe

Context

Alias 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 PContext

When

Expresses 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 PWhen

Note: 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

Subject nodes define individual test cases.

It

Defines a single spec (test case).

func It(text string, args ...any) bool

Parameters:

  • text: Description of what the spec tests
  • args: Test body function and optional decorators

Example:

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))

FIt

Focused It - only focused specs run.

func FIt(text string, args ...any) bool

PIt

Pending It - marks spec as pending (not run).

func PIt(text string, args ...any) bool

XIt

Alias for PIt.

var XIt = PIt

Specify

Alias for It. Use when "It" doesn't read naturally.

var Specify = It
var FSpecify = FIt
var PSpecify = PIt
var XSpecify = XIt

Example:

Specify("the system should handle edge cases", func() {
    // test code
})

Setup and Teardown Nodes

BeforeEach

Runs before each spec in the container.

func BeforeEach(args ...any) bool

Parameters:

  • args: Setup function and optional decorators

Example:

var book *Book

BeforeEach(func() {
    book = &Book{Title: "Test Book"}
})

It("has a title", func() {
    Expect(book.Title).To(Equal("Test Book"))
})

AfterEach

Runs after each spec in the container.

func AfterEach(args ...any) bool

Example:

var tempFile string

BeforeEach(func() {
    tempFile = createTempFile()
})

AfterEach(func() {
    os.Remove(tempFile)
})

JustBeforeEach

Runs after all BeforeEach blocks but immediately before the It block.

func JustBeforeEach(args ...any) bool

Example:

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())
    })
})

JustAfterEach

Runs immediately after the It block but before AfterEach blocks.

func JustAfterEach(args ...any) bool

Example:

JustAfterEach(func() {
    // Captures state right after test
    if CurrentSpecReport().Failed() {
        captureDebugInfo()
    }
})

BeforeAll

Runs once before all specs in an Ordered container.

func BeforeAll(args ...any) bool

Example:

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()
    })
})

AfterAll

Runs once after all specs in an Ordered container.

func AfterAll(args ...any) bool

DeferCleanup

Registers 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 arguments

Example:

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)
})

Failure Handling

Fail

Marks the current spec as failed with a message.

func Fail(message string, callerSkip ...int)

Parameters:

  • message: Failure message
  • callerSkip: Optional number of stack frames to skip for reporting

Example:

It("handles failures", func() {
    if !isValid() {
        Fail("Validation failed")
    }
})

AbortSuite

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")
    }
})

Skip

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
})

GinkgoRecover

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())
})

Configuration and State

GinkgoConfiguration

Returns the current suite and reporter configuration.

func GinkgoConfiguration() (SuiteConfig, ReporterConfig)

Example:

suiteConfig, reporterConfig := GinkgoConfiguration()
fmt.Printf("Random seed: %d\n", suiteConfig.RandomSeed)

GinkgoRandomSeed

Returns the random seed used for spec randomization.

func GinkgoRandomSeed() int64

GinkgoParallelProcess

Returns the current parallel process number (1-indexed).

func GinkgoParallelProcess() int

Example:

BeforeEach(func() {
    // Use different test data per process
    processNum := GinkgoParallelProcess()
    testData = loadTestData(processNum)
})

GinkgoLabelFilter

Returns the configured label filter expression.

func GinkgoLabelFilter() string

GinkgoSemVerFilter

Returns the configured semantic version filter.

func GinkgoSemVerFilter() string

GinkgoHelper

Marks 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
})

Output Management

GinkgoWriter

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 GinkgoWriterInterface

Example:

It("logs debug info", func() {
    GinkgoWriter.Println("Starting test")
    result := performOperation()
    GinkgoWriter.Printf("Result: %v\n", result)
    Expect(result).To(BeTrue())
})

GinkgoLogr

Logr-compatible logger that writes to GinkgoWriter.

var GinkgoLogr logr.Logger

Example:

It("uses structured logging", func() {
    logger := GinkgoLogr.WithName("test")
    logger.Info("operation started", "id", 123)
    // Perform operation
    logger.Info("operation completed")
})

GinkgoT

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
})

GinkgoTB

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
}

PauseOutputInterception

Temporarily pauses output interception.

func PauseOutputInterception()

ResumeOutputInterception

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")
})

Progress Reporting

AttachProgressReporter

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 string

Returns: Function to detach the progress reporter

Example:

BeforeEach(func() {
    detach := AttachProgressReporter(func() string {
        return fmt.Sprintf("Current operation: %s", getCurrentOp())
    })
    DeferCleanup(detach)
})

Documentation

By

Documents steps within a spec. Useful for understanding spec flow and debugging.

func By(text string, callback ...func())

Parameters:

  • text: Step description
  • callback: Optional function to execute for this step

Example:

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())
    })
})

Testing Interfaces

GinkgoTestingT

Minimal testing interface required by RunSpecs.

type GinkgoTestingT interface {
    Fail()
}

SpecContext

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 Functions

GinkgoParallelNode

Deprecated: Use GinkgoParallelProcess instead.

func GinkgoParallelNode() int

Measure

Deprecated: Removed in Ginkgo 2.0. Use the gmeasure package instead.

func Measure(_ ...any) bool

CurrentGinkgoTestDescription

Deprecated: Use CurrentSpecReport instead.

func CurrentGinkgoTestDescription() DeprecatedGinkgoTestDescription

Returns information about the currently running test. Replaced by CurrentSpecReport() which provides a more comprehensive SpecReport type.

RunSpecsWithCustomReporters

Deprecated: Custom reporters removed in Ginkgo 2.0.

func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, _ []Reporter) bool

This function simply calls RunSpecs(). Use Ginkgo's reporting nodes and 2.0 reporting infrastructure instead.

RunSpecsWithDefaultAndCustomReporters

Deprecated: Custom reporters removed in Ginkgo 2.0.

func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, _ []Reporter) bool

This function simply calls RunSpecs(). Use Ginkgo's reporting nodes and 2.0 reporting infrastructure instead.

Deprecated Types

DeprecatedGinkgoTestDescription

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().

GinkgoTestDescription

Deprecated alias for DeprecatedGinkgoTestDescription.

type GinkgoTestDescription = DeprecatedGinkgoTestDescription

Benchmarker

Deprecated: 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.

Done

Deprecated: Done channel pattern no longer supported.

type Done = internal.Done

The 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.

GinkgoTInterface

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.