blog

Lightweight BDD for iOS and OS X

by

XcodeI took a look at GitHub’s Mantle framework for iOS and Cocoa last Fall and am using it in one of my side projects this Spring. While reading through the Mantle source I noticed some dependencies on the Specta testing and Expecta matcher framework, neither of which I was familiar with. I was planning to use the Kiwi framework to implement some BDD style tests for my project, but decided to give Specta and Expecta a shot instead.

Specta is a lightweight BDD style testing framework for iOS and OS X that is built on top of OCUnit and offers tight integration with Xcode. In my experience all that’s needed is to include a Unit Test target in your Xcode project, add the Specta pod to your podfile (you are using Cocoapods, right?), update, and start writing tests. Specta uses a block-based syntax to describe your tests that’s easy to learn, and is compatible with the STAssert-style matchers included with OCUnit that you’re familiar with if you’ve written any tests for iOS or OS X.
However, Specta is even better when you use Expecta instead. Expecta is a matcher framework that includes many common matchers, supports asynchronous testing, and allows you to write custom matchers as well. It’s syntax is straightforward and so much more readable than those old STAssert macros.

// Instead of writing
STAssertEqualObjects(@"foo", @"foo", @"Expected 'foo', but was....");
// With Expecta we can write
expect(@"foo").to.equal(@"foo);

Check out the Specta and Expecta docs on GitHub for more examples and documentation. If you’re using Cocoapods you get them setup and running in a matter of minutes. Specta also works with the OCHamcrest matcher framework and the OCMock mock object framework as well if you’re already using those to write your tests.
I put together a quick demo showing how you can use Specta and Expecta in your iOS project. The demo app uses the Forecastr wrapper around the forecast.io API (get your API key first) to fetch the current temperature and conditions for Cupertino, CA. It has a single spec defined with some simple tests, clone or fork the repo and add some tests to see how failures are reported in Xcode and what other matchers are provided by Expecta.

+ more