Skip to content

Instantly share code, notes, and snippets.

@atheiman
Created November 17, 2017 22:19
Show Gist options
  • Save atheiman/ff359aca3a8b2e4d3cb2379163325544 to your computer and use it in GitHub Desktop.
Save atheiman/ff359aca3a8b2e4d3cb2379163325544 to your computer and use it in GitHub Desktop.
Stubbing methods interacting with /etc/passwd
describe 'cookbook::recipe' do
cached(:chef_run) do
ChefSpec::ServerRunner.new.converge(described_recipe)
end
it 'creates home directories' do
%w[/home/testuser1 /home/testuser2].each do |d|
expect(chef_run).to create_directory(d)
end
end
end
describe 'etc passwd reading' do
let(:users) do
[
['root', '********', 0, 0, '/root', '/bin/bash'],
['testuser1', '********', 1002, 1002, '/home/testuser1', '/bin/bash'],
['testuser2', '********', 1003, 1003, '/home/testuser2', '/bin/bash']
].map { |u| User.new(*u) }
end
before do
User = Struct.new(:name, :passwd, :uid, :gid, :dir, :shell)
allow(Etc).to receive(:getpwent).and_return(*users, nil)
end
it do
expect(user_home_dirs).to match_array(%w[/home/testuser1 /home/testuser2])
end
end
module Helper
module_function
def passwd_users
Etc.endpwent # ensure we start at the first user
users = []
loop do
user = Etc.getpwent # get the next passwd entry
puts "user: #{user}"
break if user.nil? # after all entries have been read nil is returned
users << user
end
users # return the users
end
def user_home_dirs
passwd_users.reject do |user|
%w[root hault sync shutdown].include?(user.name) ||
user.dir.include?('/usr/sbin/nologin')
end.map { |user| user.dir }
end
end
user_home_dirs.each do |d|
directory d do
action :create
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment