Loading a storyboard programatically

May 25, 2014 00:00 · 216 words · 2 minute read

I am not the world’s greatest fan of Storyboards, having been scarred by an unfortunate project involving a) a huge Storyboard b) multiple developers and c) horrific merge conflicts. That said, some people do like them, so each to their own…

If you manage to overcome the visceral loathing and need to user Storyboards in tests, you’ll hit the problem that they seem to be used semi-magically. There’s no obvious equivalent of an initWithNibFile method that you can hook into to load the thing as you kick your test case off.

The answer is actually reasonably straight forward. Create your storyboard as normal (or rely on an Xcode template if that’s your thing), then make sure that you’ve given it a Storyboard ID in the Attributes inspector. The ID you use is a text string, and Xcode doesn’t seem to care what that string is.

Then in your test, you load and instantiate your view controller in a two stage process - here’s an example Kiwi test:

it(@"should instantiate the view controller", ^{
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"ViewController"];
    [[vc shouldNot] beNil]
});

This loads the storyboard itself, then instantiates the view controller from it - the identifier string is whatever you put in the Storyboard ID field in Interface Builder.