Testing with Quick

Episode #170 | 16 minutes | published on May 21, 2015 | Uses nimble-0.4.2, quick-0.3.1
Subscribers Only
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))
            }
        }
    }

}
blog comments powered by Disqus