Episode #170

Testing with Quick

16 minutes
Published on May 21, 2015

This video is only available to subscribers. Get access to this video and 584 others.

In this episode we talk about a Swift testing framework called Quick. Quick offers a familiar BDD style syntax, some really friendly matchers, as well as support for testing asynchronous parts of our code. We'll use a Ninja class as our example, testing initialization, equality, and an asynchronous method.

Episode Links

Ninja Class

// Ninja.swift
import Foundation

public class Enemy {
    public var hitPoints = 100
    public init() {

    }
}

public class Ninja {
    public var name: String

    public init(name: String) {
        self.name = name
    }

    public func encounter(enemy: Enemy) {
        let ms = arc4random_uniform(100)
        let delta = UInt64(ms) * NSEC_PER_MSEC
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delta))
        dispatch_after(time, dispatch_get_main_queue()) {
            enemy.hitPoints -= 10
        }
    }
}


extension Ninja : Equatable {}

public func ==(lhs: Ninja, rhs: Ninja) -> Bool {
    return lhs.name == rhs.name
}

Ninja Spec

// NinjaSpec.swift
import Foundation
import NinjaGame
import Quick
import Nimble

class NinjaSpec : QuickSpec {

    override func spec() {
        var ninja = Ninja(name: "Sid")

        UIApplication.sharedApplication().delegate?.window?

        describe("initialization") {
            it("initialized the name") {
                expect(ninja.name).to(equal("Sid"))
            }
        }

        describe("equality") {
            var ninja2: Ninja!
            context("two ninjas with the same name") {
                beforeEach {
                    ninja2 = Ninja(name: "Sid")
                }

                it("should be considered equal") {
                    expect(ninja) == ninja2
                }
            }

            context("two ninjas with different names") {
                beforeEach {
                    ninja2 = Ninja(name: "Barry")
                }
                it("should not be considered equal") {
                    expect(ninja) != ninja2
                }
            }
        }

        describe("attacking") {
            it("should attack when the enemy least expects it") {
                let enemy = Enemy()
                ninja.encounter(enemy)
                expect(enemy.hitPoints).toEventually(beLessThan(100))
            }
        }
    }

}

This episode uses Nimble 0.4.2, Quick 0.3.1.