Spec-driven development with Cratis
Spec-driven development with Cratis starts by describing a feature in an event model and Given/When/Then examples before implementing it. Those examples state the intended behavior for developers and coding agents. Screenplay checks supported model scenarios in memory; code-side specifications check the implementation separately.
Suppose registration must record an author’s name. Before choosing a handler or a projection, agree on the example: when a new author registers, which event is recorded, and what should the authors screen show? That gives reviewers something concrete to compare with the code, rather than reconstructing the agreement from a diff.
Why write the spec first
Section titled “Why write the spec first”An event model shows the command, the facts it records and the state a screen reads. Given/When/Then turns that flow into an example: given earlier facts, when a command arrives, then these outcomes should follow.
Writing the example first exposes unanswered questions before implementation. Running it later checks the behavior it actually asserts, not every possible behavior of the feature. That distinction matters when a coding agent supplies the implementation: passing specs are review evidence, not permission to skip review.
The chain from model to verified code
Section titled “The chain from model to verified code”Each step produces something the next step reads. You can enter the chain at any point; Arc and Chronicle do not depend on the model-first tools.
| Step | What you have | Where it is documented |
|---|---|---|
| 1. Event model | Slices: a screen, its command, the event, the read model behind the next screen | Event modeling, Studio |
| 2. Screenplay specifications | specification blocks inside a slice in a .play file, compiled and run by the Screenplay tool for supported scenarios |
Screenplay |
| 3. Stage | Compiles .play folders, checks supported declared specifications, and renders reviewable Arc and Chronicle code for supported slice shapes |
Stage |
| 4. Arc and Chronicle code | The command, event and projection of the slice | Build a full app, capability map |
| 5. Code-side specs and replay | Executable behavior-driven development (BDD) specs in your backend’s test framework, plus Chronicle replay of read models | Testing with Cratis; Specifications for the .NET lifecycle |
| Alternative start | Prologue captures signals from an existing system and proposes a model for you to review | Prologue |
The specifications appear twice on purpose. The Screenplay specification checks the model: given these events, when this command, the model says these events follow. The code-side test checks the code: the implementation really appends them. Keeping both lets you check the modeled behavior separately from its implementation. A passing model scenario does not establish that the business rule itself is correct.
One slice, written as spec and as test
Section titled “One slice, written as spec and as test”Take the column from the testing guide: a screen registers an author, the RegisterAuthor command appends AuthorRegistered, and the Author read model feeds the authors screen.
In Screenplay, the specification lives inside the slice next to the command and the event. This follows the shape of the examples in the Screenplay specifications page, reduced to an author identifier and a name property. The identifier tells Screenplay which event source the event belongs to, the same role the author id plays in the commands below:
module Authors feature Registration slice StateChange RegisterAuthor command RegisterAuthor authorId Uuid identifier name String produces AuthorRegistered for authorId name = name event AuthorRegistered name String specification RegisteringANewAuthor when RegisterAuthor authorId = "0c9d5a8e-3b8f-4a52-9a1e-6f1d2c3b4a5e" name = "Jane Austen" then AuthorRegistered name = "Jane Austen"Run it with the Screenplay tool, which evaluates the model in memory without rendering an application or starting services:
screenplay test path/to/screenplaysThe same behavior on the code side is a command spec. With the Arc backend’s Chronicle integration configured, the handler returns the event and Arc appends it for the author id. These excerpts show the command and event, not the application’s host setup:
using Cratis.Arc.Commands.ModelBound;using Cratis.Chronicle.Events;
namespace Library.Authors;
[Command]public record RegisterAuthor(EventSourceId AuthorId, string Name){ public AuthorRegistered Handle() => new(Name);}
[EventType]public record AuthorRegistered(string Name);import io.cratis.arc.artifacts.Command;import io.cratis.arc.artifacts.CommandKey;import io.cratis.chronicle.events.EventType;
@EventTypepublic record AuthorRegistered(String name) { }
@Commandpublic record RegisterAuthor(@CommandKey String authorId, String name) { public AuthorRegistered handle() { return new AuthorRegistered(name); }}package library.authors
import io.cratis.arc.artifacts.Commandimport io.cratis.arc.artifacts.CommandKeyimport io.cratis.chronicle.events.EventType
@EventTypedata class AuthorRegistered(val name: String)
@Commanddata class RegisterAuthor(@CommandKey val authorId: String, val name: String) { fun handle(): AuthorRegistered = AuthorRegistered(name)}import { field } from '@cratis/fundamentals';import { command, key } from '@cratis/arc.core';import { eventType } from '@cratis/chronicle/events';
@eventType()export class AuthorRegistered { @field(String) name: string;
constructor(name = '') { this.name = name; }}
@command()export class RegisterAuthor { @field(String) @key() authorId = ''; @field(String) name = '';
handle(): AuthorRegistered { return new AuthorRegistered(this.name); }}The spec executes that command through Arc’s command pipeline and checks the recorded fact. Choose the same backend as above:
using Cratis.Arc.Chronicle.Testing.Commands;using Cratis.Arc.Commands;using Cratis.Arc.Testing.Commands;using Cratis.Chronicle.Events;using Cratis.Specifications;using Xunit;
namespace Library.Authors.for_RegisterAuthor;
public class when_registering_a_new_author : Specification{ readonly EventSourceId _authorId = EventSourceId.New(); readonly CommandScenario<RegisterAuthor> _scenario = new(); CommandResult _result = default!;
async Task Because() => _result = await _scenario.Execute(new RegisterAuthor(_authorId, "Jane Austen"));
[Fact] void should_accept_the_command() => _result.ShouldBeSuccessful();
[Fact] Task should_record_the_fact() => _scenario.ShouldHaveAppendedEvent<RegisterAuthor, AuthorRegistered>( _authorId, e => e.Name == "Jane Austen");
void Destroy() => _scenario.Dispose();}import io.cratis.arc.chronicle.ChronicleCommandScenario;import io.cratis.arc.chronicle.ChronicleCommandScenarios;import io.cratis.arc.generated.LibraryArcArtifactModule;import io.cratis.arc.testing.CommandScenario;import io.cratis.arc.testing.java.BlockingCommandScenario;import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class WhenRegisteringANewAuthor { @Test void recordsTheFact() { var configured = new CommandScenario<>(new LibraryArcArtifactModule(), RegisterAuthor.class); ChronicleCommandScenario chronicle = ChronicleCommandScenarios.chronicle(configured);
try (var scenario = new BlockingCommandScenario<>(configured)) { scenario.execute(new RegisterAuthor("author-1", "Jane Austen")).shouldSucceed(); }
var registered = chronicle.shouldHaveAppendedEvent("author-1", AuthorRegistered.class); assertEquals("Jane Austen", registered.name()); }}package library.authors
import io.cratis.arc.chronicle.chronicleimport io.cratis.arc.generated.LibraryArcArtifactModuleimport io.cratis.arc.testing.CommandScenarioimport kotlin.test.assertEqualsimport kotlinx.coroutines.runBlockingimport org.junit.jupiter.api.Test
class WhenRegisteringANewAuthor { @Test fun `records the fact`() = runBlocking { val scenario = CommandScenario(LibraryArcArtifactModule(), RegisterAuthor::class.java)
val result = scenario.execute(RegisterAuthor("author-1", "Jane Austen"))
result.shouldSucceed() val registered = scenario.chronicle().shouldHaveAppendedEvent<AuthorRegistered>("author-1") assertEquals("Jane Austen", registered.name) }}import { ChronicleCommandScenario } from '@cratis/arc.chronicle/testing';import { afterEach, beforeEach, describe, it } from 'vitest';import { AuthorRegistered, RegisterAuthor } from './RegisterAuthor.js';
describe('when registering a new author', () => { let scenario: ChronicleCommandScenario<RegisterAuthor>; let result: Awaited<ReturnType<typeof scenario.execute>>;
beforeEach(async () => { scenario = ChronicleCommandScenario.for(RegisterAuthor, AuthorRegistered); result = await scenario.execute({ authorId: 'author-1', name: 'Jane Austen' }); });
afterEach(async () => { await scenario.dispose(); });
it('should accept the command', () => { result.shouldBeSuccessful(); });
it('should record the fact', () => { result.shouldHaveAppendedEvent(AuthorRegistered, 'author-1', event => event.name === 'Jane Austen'); });});No HTTP or Chronicle server starts in these tests: each backend’s test support captures appended events in memory. The model-level and code-side specifications describe the same intended behavior at different levels; passing either one does not prove they agree.
In C#, Because() is the when and each [Fact] is a then; there is no Establish() because this registration needs no prior facts. TypeScript uses Vitest setup and assertions, while Kotlin and Java use JUnit. The JVM appended-event helper expects exactly one matching event; C# and TypeScript accept one or more. TypeScript’s scenario does not enforce constraints. Testing with Cratis explains these limits and adds the read-model spec; Specifications covers the .NET lifecycle methods and folder naming.
How agents use the specs as the contract
Section titled “How agents use the specs as the contract”Give the agent a reviewed example rather than asking it to infer the rule from a feature name:
- Supply the
.playfile or Given/When/Then table and identify the code-side specifications it should satisfy. - Ask it to implement the behavior and run the specifications, without changing their expected outcomes to fit its code.
- Review changes to the specifications as changes of intent. Review implementation changes against those examples and the behavior they leave untested.
Cratis AI installs rules and skills into a repository so an agent follows the conventions of the stack, including the specification style; see AI-native development and the EventModelers.ai workflow. For how agents fit into a whole delivery process, read agentic development.
Execution and rendering limits
Section titled “Execution and rendering limits”Check the capability map before choosing tools. Stage’s specification runner checks declared scenarios against modeled facts and writes results.json; it does not exercise every slice through a live generated application. Unsupported constructs are not passing scenarios. Operation specifications are syntax only and cannot be executed by the reference runner.
Stage renders a subset of slice shapes, and generated output needs review. Ordinary Given/When/Then examples also do not prove concurrency handling. Decisions that hold explains the read protection that guards an append when decision state changes.
If your next task is to test application code, start at step 5. The Arc and Chronicle testing scenarios work without the model-first tools.
Frequently asked questions
Section titled “Frequently asked questions”What is spec-driven development?
Section titled “What is spec-driven development?”Spec-driven development is a way of building software where the specification is written first and stays the contract. In Cratis the specification is the event model plus Given/When/Then specifications. Code is written or generated against them and checked by running them.
Is this the same as test-driven development?
Section titled “Is this the same as test-driven development?”They overlap. Test-driven development writes a failing test before the code, usually in the language of the implementation. Here the spec is written one level earlier, in the event model and in Screenplay, in terms a domain expert can read. The executable code-side specs are then the test-first part.
Do I need Screenplay and Stage to do it?
Section titled “Do I need Screenplay and Stage to do it?”No. The code side works alone: Arc command scenarios and supported Chronicle in-process scenarios need none of the model-first tools. Screenplay and Stage add a model-level spec and, for supported shapes, generated code.
Which languages can run the specifications?
Section titled “Which languages can run the specifications?”The testing guide shows command and read-model specs for the Arc and Chronicle client languages, with differences between backends, and lists what Elixir does not support yet. The Specifications library itself targets .NET with xUnit or NUnit. See Testing with Cratis.
Can a coding agent write the specifications too?
Section titled “Can a coding agent write the specifications too?”It can draft them, but a person should approve them. A spec an agent writes for its own code only proves the code does what the agent wrote. Have the agent propose the specification from the event model, review it as intent, then let it implement.
When is it the wrong fit?
Section titled “When is it the wrong fit?”For a throwaway prototype, a pure infrastructure change, or a very small assertion, a full model and specification adds more than it returns. The Specifications page lists where plain xUnit or NUnit tests are the better choice.