SPM Test Dependencies

I’ve built a few toy libraries with the Swift Package Manager, and one of friction points was writing tests with XCTest. I’ve become really familiar with writing tests in a BDD style with Quick and Nimble (and Kiwi in the past) and so it’s weird when they aren’t there. There used to be a way to declare dependencies for test targets in a Package.swift file that was since removed, which led to some creative workarounds involving a separate executable target to run tests, but this wasn’t ideal.

I was excited to see that the Swift 4 version of the Package.swift format allowed declaring dependencies for test targets, which means that it’s now possible to include libraries like Quick and Nimble more naturally. Here’s an example:

// Package.swift
// swift-tools-version:4.0
import PackageDescription

let package = Package(
    name: "Sample",
    products: [
        .library(
            name: "Sample",
            targets: ["Sample"]),
    ],
    dependencies: [
        .package(url: "git@github.com:Quick/Quick.git", from: "1.1.0"),
        .package(url: "git@github.com:Quick/Nimble.git", from: "7.0.1"),
    ],
    targets: [
        .target(
            name: "Sample",
            dependencies: []),
        .testTarget(
            name: "SampleTests",
            dependencies: ["Sample", "Quick", "Nimble"]),
    ]
)

And then they can be used as you normally would:

import Quick
import Nimble
@testable import Sample

class SampleSpecs: QuickSpec {
    override func spec() {
        describe("an example") {
            it("passes") {
                expect(true).to(beTrue())
            }
        }
    }
}

And tests are run and display just like when using XCTest:

$ swift test

Compile Swift Module 'SampleTests' (1 sources)
Test Suite 'All tests' started at 2017-08-14 17:19:42.618
Test Suite 'SamplePackageTests.xctest' started at 2017-08-14 17:19:42.619
Test Suite 'SampleSpecs' started at 2017-08-14 17:19:42.619
Test Case '-[SampleTests.SampleSpecs an example, passes]' started.
Test Case '-[SampleTests.SampleSpecs an example, passes]' passed (0.195 seconds).
Test Suite 'SampleSpecs' passed at 2017-08-14 17:19:42.814.
         Executed 1 test, with 0 failures (0 unexpected) in 0.195 (0.195) seconds
Test Suite 'SamplePackageTests.xctest' passed at 2017-08-14 17:19:42.814.
         Executed 1 test, with 0 failures (0 unexpected) in 0.195 (0.195) seconds
Test Suite 'All tests' passed at 2017-08-14 17:19:42.814.
         Executed 1 test, with 0 failures (0 unexpected) in 0.195 (0.195) seconds