Skip to content

Instantly share code, notes, and snippets.

@randomeizer
Last active June 24, 2021 02:37
Show Gist options
  • Save randomeizer/11a6b725c81a2cee351b24bb8622d0c8 to your computer and use it in GitHub Desktop.
Save randomeizer/11a6b725c81a2cee351b24bb8622d0c8 to your computer and use it in GitHub Desktop.
`given` function to simplify data-driven testing with Quick/Nimble
//
// given.swift
// Support/Tests
//
// Created by David Peterson on 23/6/21.
//
/**
This can then be used to provide multiple examples of data to iterate tests over.
For example, this will result in three different tests occurring:
```swift
given(
(1, plus: 1, is: 2),
(1, plus: 2, is: 2),
(1, plus: 3, is: 4)
) { (a, b, result) in
it("\(a) plus \(b) is \(result)") {
expect(a + b).to(equal(result))
}
}
```
In this case, the second item (1 plus 2) has an error in the data, and will fail on the `expect` line, since `1 + 2 != 2`.
In this case, the error itself won't indicate which line of data failed, but you can tell from the generated `it` test name, since it interpolates the values into the title, which in this case would report that `1_plus_2_is_2()` failed. However, if you want to get more specific, you can use the `#line` feature of Swift to grab the line number, then pass it to `expect` to report the specific line, like so:
```swift
given(
(1, plus: 1, is: 2, line: #line),
(1, plus: 2, is: 2, line: #line),
(1, plus: 3, is: 4, line: #line)
) { (a, b, result, line: UInt) in
it("\(a) plus \(b) is \(result)") {
expect(line: line, a + b).to(equal(result))
}
}
```
*Note:* It's important to specify `line: UInt` in the input signature, since `UInt` is the type that the `expect` function requires for its `line:` parameter.
This will now highlight the second row of data as failing instead of the `expect` line.
- Parameter data: The list of input data to iterate over.
- Parameter then: The closure that will be called for each data item.
*/
func given<Data>(_ data: Data..., then: (_: Data) -> Void) {
for item in data { then(item) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment