Hi all!
I've been banging my head against this for the past couple of days and I'm pretty stuck. I've started implementing rspec tests for a class that uses a hiera lookup and then uses the looked up value to control part of its logic. A simplified version:
class mytest {
$mycondition = hiera('my::condition')
if $mycondition {
...
}
}
My spec_helper looks like this:
require 'rubygems'
require 'puppetlabs_spec_helper/module_spec_helper'
RSpec.configure do |c|
c.hiera_config = 'spec/fixtures/hiera/hiera.yaml'
end
So far, so standard. What I want to be able to test, obviously, is making sure that when $mycondition is true, the resources in the if statement are added to the catalog, and if $mycondition is false, they aren't.
So, my spec in spec/classes/mytest_spec.rb looks like this:
require 'spec_helper'
describe 'mytest' do
let(:node) { 'truecondition' }
if {
should compile
}
end
My hiera.yaml file looks like this:
---
:backends:
- yaml
:yaml:
:datadir: 'spec/fixtures/hieradata'
:hierarchy:
- "%{::fqdn}"
and my spec/fixtures/hieradata/truecondition.yaml looks like this:
---
my::condition: false
With this setup, my spec class returns an error:
Failures:
1) mytest should compile into a catalogue
without dependency cycles
Failure/Error: should compile
error during compilation: Evaluation Error: Error while evaluating a Func
tion Call, Could not find data item my::condition in any Hiera data file
and no default supplied at C:/puppet/mytest/spec/fixtures/modules/mytest/manifests/init.pp:3:22 on node truecondition
# ./spec/classes/mytest_spec.rb:7:in `block (2 levels) in
<top (required)>'
Finished in 0.4212 seconds (files took 2.42 seconds to load)
1 example, 1 failure
Ultimately, I thought I could specify a different context for each state of $mycondition: true and false, so my test would look like:
require 'spec_helper'
describe 'mytest' do
context "with mycondition => true" do
let(:node) { 'truecondition' }
if {
should compile
}
end
context "with mycondition => false" do
let(:node) { 'falsecondition' }
if {
should compile
}
end
end
I tried having my contexts set a fact that hiera could use to select which yaml file it got data from: didn't work. I tried having a different hiera.yaml file, one for true and one for false, that would load a different common.yaml (since common.yaml seems to work, but nothing else), and that didn't work. The example above was the last thing I tried, since rspec-puppet is supposed to provide the fqdn fact, so I thought setting the node might help it switch. Failure on all sides!
At this point, I'm almost ready to throw in the towel. There has to be some way to change what values hiera supplies so I can test all branches of my code, but I'm not sure how to do it. Any suggestions or alternatives would be welcome.
Thanks!