Skip to content

Instantly share code, notes, and snippets.

@MP0w
Created January 13, 2017 11:32
Show Gist options
  • Save MP0w/36c9d6397c302806b7ff4419d71065ef to your computer and use it in GitHub Desktop.
Save MP0w/36c9d6397c302806b7ff4419d71065ef to your computer and use it in GitHub Desktop.
A matcher to spy
//
// CallRecordMatcher.swift
// Verse
//
// Created by Alex Manzella on 13/01/17.
// Copyright © 2017 Verse Technologies, Inc. All rights reserved.
//
import Foundation
import Nimble
protocol Spy: class {
var recordedFunctions: [String] { get set }
}
extension Spy {
func record(function: String = #function) {
recordedFunctions.append(function)
}
}
func call(_ function: String) -> CallRecordMatcher {
return CallRecordMatcher(function: function)
}
struct CallRecordMatcher: Matcher {
enum Failure: Error {
case invalidSpy
}
typealias ValueType = Spy
let function: String
private func composeFailureMessage(_ message: FailureMessage, negated: Bool) {
message.expected = "Expected \(function)"
let negation = negated ? "not" : ""
message.to = "to \(negation) be called"
message.postfixMessage = ""
message.actualValue = nil
}
private func didCallFunction(_ actualExpression: Expression<Spy>) throws -> Bool {
guard let spy = try actualExpression.evaluate() else {
throw Failure.invalidSpy
}
return spy.recordedFunctions.contains(function)
}
func matches(_ actualExpression: Expression<Spy>,
failureMessage: FailureMessage) throws -> Bool {
composeFailureMessage(failureMessage, negated: false)
return try didCallFunction(actualExpression)
}
func doesNotMatch(_ actualExpression: Expression<Spy>,
failureMessage: FailureMessage) throws -> Bool {
composeFailureMessage(failureMessage, negated: true)
return try !didCallFunction(actualExpression)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment