Test iOS Business State Machines on a Cloud Mac

Test iOS Business State Machines on a Cloud Mac

Test iOS Business State Machines on a Cloud Mac

The review screen no longer shows a Publish button, yet a callback on an older screen still sends drafts to the publishing endpoint. The problem is not the button: the business layer has no single set of rules governing state transitions. Encoding those rules in a pure Swift state machine and running it as a pre-build check on a cloud Mac can catch workflow gaps earlier than manual testing.

This example uses five states: draft, in review, approved, published, and cancelled. The tests make no network calls, launch no simulator, and require no signing assets. They verify business rules, not the appearance of the interface.

Define the Contract

Start by writing the product rules as a separate checklist: a draft can be submitted; an item in review can be approved or sent back; an approved item can be published; and cancellation is allowed in all three nonterminal states. Published and cancelled are terminal states and reject every event.

Here, a repeated submission is deliberately treated as a rejection, not a success. If the business requires an idempotent response, define that result explicitly rather than leaving each caller to interpret it differently.

“The event was received” does not mean “the transition completed.” Tests must check both the acceptance result and the final state, not just whether the function throws an error.

When an event is rejected, the original state must remain unchanged. Keep notifications, network requests, and persistence outside the transition decision so that publishing side effects cannot run before approval.

Implement a Pure Transition Function

Save the following two Swift code blocks, in order, in a single file named workflow-check.swift. The transition function takes only a state and an event, then returns either the target state or nil. The caller updates its state only when the event is accepted.

enum State: CaseIterable, Hashable {
    case draft, reviewing, approved, published, cancelled
}

enum Event: CaseIterable, Hashable {
    case submit, approve, reject, publish, cancel
}

func transition(_ state: State, _ event: Event) -> State? {
    switch (state, event) {
    case (.draft, .submit):
        return .reviewing
    case (.reviewing, .approve):
        return .approved
    case (.reviewing, .reject):
        return .draft
    case (.approved, .publish):
        return .published
    case (.draft, .cancel),
         (.reviewing, .cancel),
         (.approved, .cancel):
        return .cancelled
    default:
        return nil
    }
}

struct Workflow {
    private(set) var state: State

    mutating func send(_ event: Event) -> Bool {
        guard let next = transition(state, event) else {
            return false
        }
        state = next
        return true
    }
}

Do not return the original state from the default branch to indicate success. That would make a valid self-transition indistinguishable from an invalid operation, leaving callers unable to decide reliably whether to perform follow-up actions.

Enumerate Every State–Event Pair

Five states and five events produce twenty-five combinations. The checklist must come from the business contract defined above. Do not generate expected results by calling the transition function; otherwise, an implementation error will be reproduced in the test.

The independent dictionary below lists the seven valid transitions. Every other combination must be rejected. Use precondition rather than ordinary debug assertions, and do not pass optimization options that disable checks when running the script.

let expected: [State: [Event: State]] = [
    .draft: [
        .submit: .reviewing,
        .cancel: .cancelled
    ],
    .reviewing: [
        .approve: .approved,
        .reject: .draft,
        .cancel: .cancelled
    ],
    .approved: [
        .publish: .published,
        .cancel: .cancelled
    ]
]

for state in State.allCases {
    for event in Event.allCases {
        var workflow = Workflow(state: state)
        let target = expected[state]?[event]
        let accepted = workflow.send(event)
        precondition(accepted == (target != nil))
        precondition(workflow.state == (target ?? state))
    }
}

var visited: Set<State> = [.draft]
var pending: [State] = [.draft]

while let state = pending.popLast() {
    for event in Event.allCases {
        if let next = transition(state, event),
           visited.insert(next).inserted {
            pending.append(next)
        }
    }
}

precondition(visited == Set(State.allCases))

These checks cover both the acceptance result and preservation of the original state. For example, a publish event received while an item is in review must be rejected, and the item must remain in review. Returning failure after already changing the state to published is not acceptable.

Inspect the Workflow Graph

Single-step tests check each edge, while the reachability check traverses the entire graph starting from draft. If you add a state but forget to connect it to an entry path, the final assertion will fail even if every existing transition is correct.

Reachability alone, however, does not prove that the workflow is complete. Production projects should also test three event sequences: submit, reject, and submit again; submit, approve, publish, and publish again; and cancel, followed by every event in succession. These check the rework path, repeated operations, and the absorbing behavior of terminal states, respectively.

If a state can only be restored from historical data and does not need to be reachable from draft, include it in an explicit set of recovery entry states instead of removing the reachability check. Traverse from each entry separately, preserving the distinction between states in the normal workflow and those in the recovery workflow.

Wire the Check into CI

Run the standalone script on the cloud Mac before running the project’s tests. Create check-workflow.sh with the following contents, then invoke it with bash check-workflow.sh:

set -euo pipefail
cd "$(dirname "$0")"
xcrun swift --version
xcrun swift workflow-check.swift

If the script exits normally without output, the checks have passed. An assertion failure returns a nonzero exit status and blocks subsequent tasks. Keep both files in the same directory so that a different pipeline working directory does not cause the check to be skipped.

This standalone example duplicates the business implementation for demonstration purposes. In a real integration, put the transition core in a module shared by the app and its tests, and keep only the independent expectations in the test. This prevents the script from staying correct while the application code drifts away.

Finally, verify that the check can fail: temporarily allow drafts to be published directly, confirm that the pipeline goes red, and then revert the change. Concurrent requests, persistence failures, and process restarts still need separate tests. A pure state machine makes each decision explicit; it does not replace transaction boundaries. Whenever you add a state, review the valid transitions, invalid transitions, entry states, and terminal states together. Only then is the workflow change complete.

Frequently asked questions

Do illegal transitions need tests if their buttons are hidden?

Yes. Stale screens, duplicate callbacks, and direct business-layer calls can bypass UI restrictions. The state machine must reject illegal events without changing state.

Do passing state-machine tests prove concurrency safety?

No. They validate individual transitions. Concurrent writes still require serialization, version checks, or transactions, plus separate race-condition tests.

Add a dedicated Mac to your build queue

An entire physical Mac dedicated to your tasks. Choose a model, billing period, and node to set up your team’s own macOS runner.

Rent now

Connect a runner and build today

Choose a model and node, and dedicate an entire physical Mac to your tasks.