Skip to content

Instantly share code, notes, and snippets.

@cdenneen
Created June 8, 2018 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdenneen/78502c5c5bb46e1f8e0e661276f099fc to your computer and use it in GitHub Desktop.
Save cdenneen/78502c5c5bb46e1f8e0e661276f099fc to your computer and use it in GitHub Desktop.
RSpec stubbing out a file
class profile::master {
file { '/etc/puppetlabs/puppetserver/ssh/id-control_repo.rsa':
ensure => file,
owner => 'pe-puppet',
mode => '0600',
content => file('/etc/puppetlabs/id-control_repo.rsa'),
}
}
require 'spec_helper'
describe 'profile::master' do
on_supported_os(
supported_os: [
{
'operatingsystem' => 'CentOS',
'operatingsystemrelease' => [
'7',
],
},
],
).each do |os, facts|
context "on #{os}" do
let(:facts) do
facts.merge(
puppetversion: Puppet.version,
)
end
before(:each) do
allow(File).to receive(:file?).and_call_original
allow(File).to receive(:file?).with('/etc/puppetlabs/id-control_repo.rsa').and_return(true)
allow(File).to receive(:exist?).and_call_original
allow(File).to receive(:exist?).with('/etc/puppetlabs/id-control_repo.rsa').and_return(true)
allow(File).to receive(:read).and_call_original
allow(File).to receive(:read).with('/etc/puppetlabs/id-control_repo.rsa').and_return('foo')
allow(File).to receive(:open).and_call_original
allow(File).to receive(:open).with('/etc/puppetlabs/id-control_repo.rsa', 'w') { 'foobar' }
# Doing this says expected '/etc/puppetlabs-id-control_repo.rsa' but got all json files it could find recursively.
# Puppet::Parser::Functions.newfunction(:file, type: :rvalue) { |args|
# #raise ArgumentError, 'expected foobar' unless args[0] == 'foobar'
# 'hello world'
# }
end
#
# Complains undefined method scope (which is supposedly available in rspec-puppet > 2.2.0)
#
# before(:each) { scope.expects(:file).with('/etc/puppetlabs/id-control_repo.rsa').returns('file content') }
%w[profile::master].each do |puppet_class|
it {
expect(File).to receive(:open).and_call_original
expect(File).to receive(:open).with('/etc/puppetlabs/id-control_repo.rsa','r') { 'foobar' }
expect(File).to receive(:read).and_call_original
expect(File).to receive(:read).with('/etc/puppetlabs/id-control_repo.rsa').and_return('contents')
is_expected.to contain_class(puppet_class)
}
end
it { is_expected.to compile.with_all_deps }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment