2

If I have a chef recipe with the following attribute

node.default["cookbook"]["directory"] = %w(/mnt/directory1 /mnt/directory2)

    node["cookbook"]["directory"].each do |dir|
      directory dir do
        owner "user"
        mode 0644"
        action :create
      end
    end

How would I write a chefspec test that handles an array of directories to be created based on the attribute?

Thank you for your help.

2 Answers2

2

You could also do

%w(/mnt/directory1 /mnt/directory2).each do |dir|
  expect(chef_run).to create_directory(dir)
end

UPDATE: Sorry, a little more experience and I can now give you a better answer.

Yes, the above works, but if you really want to make it great, do this...

my_directories = %w(/test/1 /other_test/2)

let(chef_run) do
  ChefSpec::SoloRunner.new do |node|
    node.default["cookbook"]["directory"] = my_directories
  end.converge(described_recipe)
end

my_directories.each do |dir|
  expect(chef_run).to create_directory(dir)
end

This will allow you to keep the list of directories and the tests together in a single file. If the list in your attributes.rb were to change, it wouldn't break the test. It also lets you use totally dummy names for the test directories, which I find beneficial.

Tejay Cardon
  • 4,193
  • 2
  • 16
  • 31
1
expect(chef_run).to create_directory('/mnt/directory1')
expect(chef_run).to create_directory('/mnt/directory2')
coderanger
  • 52,400
  • 4
  • 52
  • 75