Gherkin Generator
Published on · Updated · 15 min
The problem with manual specs
Gherkin is a powerful standard for BDD (Behavior-Driven Development). .feature files describe expected behavior in natural language: Given, When, Then. Readable by everyone — product owners, QA, developers.
But writing these specs by hand quickly becomes painful:
Repetitive — The same structures, over and over
Error-prone — One typo and the test no longer matches
No validation — Nothing checks consistency before execution
Heavy maintenance — Synchronizing specs and code is hard work
Mass generation impossible — How do you create 500 load test scenarios?
No import — Your tests exist in CSV or Excel, but impossible to convert them
What if you could do everything programmatically?
The solution: swift-gherkin-generator
Gherkin Generator is a complete Swift library for the .feature file lifecycle. Instead of writing Gherkin by hand, you build it in code — with validation, autocompletion, and the full power of Swift.
Result: an immutable, validated Feature object, ready to be exported to .feature, JSON or Markdown.
It's no longer just a generator. It's a complete toolkit: builder, parser, validator, formatter, exporter, importer, streaming, batch processing, and CLI.
Fluent and expressive API
The API is designed to reflect Gherkin's natural structure. Each method returns a new copy — everything is immutable and Sendable.
Scenarios with continuations
Chain And and But steps after any primary step:
Shared backgrounds
Define common preconditions executed before each scenario. The closure receives a BackgroundBuilder:
Scenario Outlines with Examples
Use addOutline for parameterized scenarios. Placeholders in angle brackets (<email>) are substituted from the examples table:
Named and tagged example blocks are also supported via .examples(_:name:tags:).
Data Tables
Attach a data table to any step. The first row is the header:
Doc Strings
Attach multi-line text with an optional media type:
Tags and organization
Apply tags at the feature level with .tags() and at the scenario level with .scenarioTags(). Tags are used for filtering, categorization, and hook targeting:
Rules (Gherkin 6+)
Group scenarios under named business rules to structure complex features:
Mass generation
The real power: generate hundreds of scenarios programmatically. The immutable API is used with var and reassignment:
For a mutating approach, use appendScenario(_:) or appendOutline(_:).
Built-in validation
Before export, validate your features against 5 built-in rules. The validator reports all errors found, not just the first one:
The 5 built-in rules
| Rule | Checks |
|---|---|
StructureRule | Each scenario has at least one Given and one Then |
CoherenceRule | No duplicate consecutive steps |
TagFormatRule | Tags are non-empty and have no spaces |
TableConsistencyRule | Consistent columns, no empty cells |
OutlinePlaceholderRule | Each |
Custom rules
Conform to the ValidationRule protocol to add your own checks. Rules are composable:
Batch validation
BatchValidator is an actor that parses and validates all .feature files in a directory in parallel:
streamValidation(at:) provides an AsyncStream for progressive reporting.
Multi-format: import and export
Parsing .feature files
GherkinParser uses a recursive descent parser. It automatically detects the language from a # language: header or falls back to English:
Also parses directly from a Gherkin string:
CSV import
Map CSV columns to Gherkin step types via CSVImportConfiguration. Each row becomes a scenario:
Custom delimiter and optional tag column supported.
JSON import (round-trip)
JSONFeatureParser decodes JSON produced by GherkinExporter, guaranteeing a perfect round-trip — export to JSON then reimport produces an identical Feature:
Plain text import
Parse informal text into scenarios. Lines starting with Given/When/Then become steps, --- separates scenarios:
All prefixes and the separator are configurable via PlainTextImportConfiguration.
Excel import (.xlsx)
ExcelParser reads .xlsx files natively thanks to a built-in ZIP/OOXML reader — no third-party dependencies. Cross-platform: macOS, iOS, Linux via the system zlib library.
The tagColumn parameter maps a column to per-scenario tags (space or comma-separated). The sheetIndex parameter selects the worksheet to read.
Batch import
BatchImporter is an actor that scans a directory of .feature files and parses them in parallel:
streamDirectory(at:) provides an AsyncStream for progressive processing.
Multi-format export
GherkinExporter writes a feature to your chosen format — .feature, JSON or Markdown:
Render in memory without writing to disk:
Formatting
GherkinFormatter converts a Feature to properly indented Gherkin with aligned tables. Three presets available:
| Preset | Description |
|---|---|
.default | 2-space indentation, standard spacing |
.compact | Minimal whitespace |
.tabs | Tab indentation |
Streaming and batch processing
For large volumes, the library provides dedicated actors with AsyncStream patterns.
Streaming export
StreamingExporter is an actor that writes features line by line, without loading everything into memory. Suitable for features with hundreds of scenarios:
Get an AsyncStream<String> of formatted lines for custom processing:
Track export progress:
Batch export
BatchExporter is an actor that exports multiple features to individual files in a target directory. Files are written in parallel via TaskGroup. Titles are automatically slugified to filenames, and duplicates receive numeric suffixes (login.feature, login-1.feature, login-2.feature):
Track progress with exportAllWithProgress:
Native multi-language
Gherkin supports 70+ languages. Gherkin Generator does too — with official keywords from Cucumber's gherkin-languages.json.
15 common languages have static shortcuts: .english, .french, .german, .spanish, .italian, .portuguese, .japanese, .chinese, .russian, .arabic, .korean, .dutch, .polish, .turkish, .swedish.
Access any language by ISO code or list all available languages:
The parser automatically detects # language: directives and the formatter produces output with the correct localized keywords.
CLI included
gherkin-gen is a command-line tool with 7 subcommands for composing, validating, and converting .feature files directly from the terminal.
Installation
generate — Generate a .feature
Options --given, --when, --then, and --tag are repeatable. --language for non-English features (default: en).
validate — Validate files
--strict enables all rules by default. --quiet suppresses success messages.
parse — Analyze structure
export — Convert format
batch-export — Batch export
convert — Import from CSV/JSON/TXT/Excel
Customizable columns with --scenario-column, --given-column, --when-column, --then-column, --tag-column. CSV delimiter with --delimiter.
languages — Explore languages
Installation
Swift Package Manager
Requirements
Swift 6.2+ with strict concurrency
Xcode 26+ or compatible Swift toolchain
Platforms: iOS 17+ · macOS 14+ · tvOS 17+ · watchOS 10+ · visionOS 1+ · Mac Catalyst 17+ · Linux
Integrations
Generated .feature files are compatible with all Gherkin tools:
| Tool | Language | Compatibility |
|---|---|---|
Cucumber | Ruby, Java, JS | Native |
SpecFlow | .NET | Native |
Behave | Python | Native |
XCTest-Gherkin | Swift | Native |
Gherkin Testing | Swift | Atelier Socle Ecosystem |
Atelier Socle Gherkin Ecosystem
Gherkin Generator is part of a set of complementary tools for a complete BDD workflow in Swift:
Gherkin Generator (this library) — Compose, validate, import and export
.featurefilesGherkin Testing — Execute native BDD tests with Swift Macros (
@Feature,@Given,@When,@Then)
Two complementary tools: one generates specs, the other executes them.
Under the hood
Swift 6.2 strict concurrency — All public types are
Sendable, actors for shared state,async/awaiteverywhereZero dependencies — Pure Swift standard library (only swift-argument-parser for CLI)
Cross-platform — macOS, iOS, tvOS, watchOS, visionOS, Mac Catalyst, Linux
Recursive descent parser — Complete parsing of
.featurefiles with automatic language detectionBuilt-in ZIP/OOXML reader — Native Excel import via
zlib, no third-party dependenciesAsyncStream patterns — Streaming export, batch import and validation for large volumes
467 tests — 96%+ coverage, 6 end-to-end showcase test suites
DocC catalog — Complete documentation with 8 articles and 6 symbol extensions
CI/CD — GitHub Actions (lint, build, test, coverage, 5 platforms), automated release with macOS and Linux binaries
Links
GitHub - atelier-socle/swift-gherkin-generator: A Swift library for composing, validating, importing, and exporting Gherkin .feature files programmatically.
A Swift library for composing, validating, importing, and exporting Gherkin .feature files programmatically. - atelier-socle/swift-gherkin-generator