Search code examples
rspecpuppetrspec-puppet

how to add template file in rspec-puppet


I have below manifests for sudo user, loading template file

class sudo {
  if $::operatingsystemmajrelease < 7 {
    $variable = $::operatingsystemmajrelease ? {
      '6' => $::fqdn,

    }
    file { '/etc/sudoers' :
      ensure  => present,
      owner   => 'root',
      group   => 'root',
      mode    => '0440',
      content => template('sudo/sudoers.erb'),
    }
  }
}

Below is my rspec file

vim test_spec.rb
require 'spec_helper'
describe 'sudo' do
  it { should contain_class('sudo')}
  let(:facts) {{:operatingsystemmajrelease => 6}}

  if (6 < 7)
    context "testing sudo template with rspec" do
    let(:params) {{:content => template('sudo/sudoers.erb')}}
    it {should contain_file('/etc/sudoers').with(
      'ensure' => 'present',
      'owner'   => 'root',
      'group'   => 'root',
      'mode'    => '0440',
      'content' => template('sudo/sudoers.erb'))}
  end
  end
end

getting below error when run "rake spec"

.F
Failures:
  1) sudo testing sudo template with rspec
     Failure/Error: 'content' => template('sudo/sudoers.erb'))}
     NoMethodError:
       undefined method `template' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x7f5802e70bd8>
     # ./spec/classes/test_spec.rb:17
Finished in 0.16067 seconds
2 examples, 1 failure
Failed examples:
rspec ./spec/classes/test_spec.rb:12 # sudo testing sudo template with rspec
rake aborted!
ruby -S rspec spec/classes/test_spec.rb failed

Can any one guide me how to test template with rspec-puppet. I surfed net also breaking my head more than two days none helped.


Solution

  • template is a function of the Puppet parser and as such is not available to your unit tests.

    If you really want to use your existing template as a fixture, you will have to have to manually evaluate its ERB code.

    The much better unit testing approach would be to hard-code test data right in the test code.

    if (6 < 7)
      context "testing sudo template with rspec" do
      let(:params) {{:content => 'SPEC-CONTENT'}}
      it {should contain_file('/etc/sudoers').with(
        'ensure' => 'present',
        'owner'   => 'root',
        'group'   => 'root',
        'mode'    => '0440',
        'content' => 'SPEC-CONTENT'}
      end
    end
    

    Using actual valid templates is more interesting in the realms of acceptance or perhaps integration testing.