Including additional resources in your rspec-puppet tests

I’m a strong advocate of creating unit tests for your puppet code with rspec-puppet. I’ve written a number of articles on tests before, so here’s one more.

When you’re testing a class, sometimes there’s an expectation that it’s used alongside another class or resource. But your test is only against your class, so how do you add the other resource to the catalog? As an example, let’s look at the module jlambert121/puppet and how some of the subclasses in the module are tested, specifically puppet::server::install. The top level describe statement ensures that the class puppet::server::install is present. It does not ensure that some of the other classes it relies upon are present.

This is done through the : :pre_condition statements at the beginning of each 2nd level describe, starting on line 3:

  let(:pre_condition) { 'class {"::puppet": server => true}' }

Other describe blocks instantiate the class with different parameters, as needed for the individual test.

In the : :pre_condition, you can add any Puppet DSL you want. I would not suggest going overboard, but including or instantiating another class or a small number of resources can be very helpful. This can be especially helpful with profile classes, where you may want to test behavior when another profile is present, e.g. testing an application profile with multiple webserver profiles.

I did not find the : :pre_condition statement documented anywhere in the rspec-puppet docs, so I hope this helps others discover it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s