CocoaPods: The Elegant Solution To Installing The Same Pod In Multiple Targets

One of the most exciting things about Xcode 7 is the ability to natively UI Test (thanks Apple!). So of course that was my priority when I started a new Xcode 7 / Swift 2 project. I really enjoy using Quick and Nimble for my unit tests, so I wanted to use these libraries for my UI Testing as well.

Installing Quick and Nimble is easy with CocoaPods. The issue, however, is that you need to install Quick and Nimble only to your test targets.

The Ugly But Works Solution

The initial way to do it is to have Quick and Nimble in two targets in your Podfile:

# Podfile

platform :ios, '9.0'

use_frameworks!

# My other pods

target 'MyTests' do
    pod 'Quick', '0.5.0'
    pod 'Nimble', '2.0.0-rc.1'
end

target 'MyUITests' do
    pod 'Quick', '0.5.0'
    pod 'Nimble', '2.0.0-rc.1'
end

I did not like repeating the Quick and Nimble twice here – every time I need to upgrade the versioning, I’ll need to change it in two places…

The Wrong Solution

So I Googled around, and found that I need to be using link_with. I immediately assumed that everything below link_with only applied to the targets I specified:

# Podfile

platform :ios, '9.0'

use_frameworks!

# My other pods

link_with 'MyTests', 'MyUITests'

pod 'Quick', '0.5.0'
pod 'Nimble', '2.0.0-rc.1'

Turns out, I was completely wrong about what link_with actually does and how it works. It ended up installing Quick and Nimble to my main app target in addition to my testing targets!

The Elegant Solution

So I went to straight to the expert – Core Contributor to CocoaPods @NeoNacho, who pointed me to the following elegant solution:

# Podfile

platform :ios, '9.0'

use_frameworks!

# My other pods

def testing_pods
    pod 'Quick', '0.5.0'
    pod 'Nimble', '2.0.0-rc.1'
end

target 'MyTests' do
    testing_pods
end

target 'MyUITests' do
    testing_pods
end

I keep forgetting that a Podfile is just a ruby file! Thanks @NeoNacho for saving the day!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.