I have a puppet cookbook rspec sample test like below
it {
is_expected.to contain_file('/etc/resolv.conf')
.with(
'ensure' => 'file',
'owner' => 'root',
'group' => 'root',
'mode' => '0444',
'validate_cmd' => '/var/tmp/checkdns_nameservers.sh',
)
.with_content(resolvconf_contents)
.that_notifies('Service[sshd]')
.that_notifies('Service[nscd]')
}
The problem is that this just checks the existence of validate_cmd in the manifest.
I have to mock the validate_cmd function and returns true/false and Based on that I have to check the contents of the file newly created. How can I mock the validate_cmd command using rspec module ? Any help would be highly appreciated !!
The short answer is, it is not possible, and you would need to use a tool like Beaker, Test Kitchen etc.
For a longer answer, I direct you to the Rspec-puppet tutorial:
There are a lot of people confused by the purpose of these tests as they can’t test the result of the manifest on a live system. That is not the point of rspec-puppet. Rspec-puppet tests are there to test the behaviour of Puppet when it compiles your manifests into a catalogue of Puppet resources.
The key point is Rspec-puppet never applies the catalog that it compiles; it only inspects the compiled catalog and allows you to make assertions about what is there. But to observe the behaviour in response to differences about what your validate_cmd
does, you do need to apply the catalog on a real system.
Of course, it won't be trivial to set up systems in Beaker or Test Kitchen such that your script will return two different values either. Besides, what would you really be testing. Aren't you testing whether Puppet itself does what it promises to do? If so, you really shouldn't try to test that.
Or, is this a script that you wrote yourself? If so, consider using a Bash unit testing framework like shunit2 or BATS instead. Prove, instead, that your shell script behaves the way you expect it to in response to the OS.