1

In Ruby, * is used to represent the name of a file.

For example, /home/user/*.rb will return all files ending with .rb. I want to do something similar in Chef InSpec.

For example:

describe file ('home/user/*') do
  it {should_not exist }
end

It should give me all the files inside /home/user directory and check that no file exists inside this directory. In other words, I want to check if this directory is empty or not in Chef.

How can I do that?

james.garriss
  • 12,959
  • 7
  • 83
  • 96
saurg
  • 327
  • 1
  • 3
  • 17

2 Answers2

2

* for globs is mostly a shell feature, and as you might expect the file resource doesn't support them. Use a command resource instead:

describe command('ls /home/user') do
  its(:stdout) { is_expected.to eq "\n" }
end
coderanger
  • 52,400
  • 4
  • 52
  • 75
  • Also can you tell me about this syntax `its(:stdout) { is_expected.to eq "\n" }`. Its not chef InSpec and what is resource `is_expected` ? – saurg Aug 04 '16 at 05:34
  • That's a mix of syntax from RSpec itself and the `rspec-its` gem. Neither are specific to InSpec. Equivalent to `it { expect(subject.stdout).to eq "\n" }` just with a little less-ish typing and a little more readable as a sentence. – coderanger Aug 04 '16 at 07:23
1

Here's an alternate approach that tests for the existence of the directory, and if it exists it uses Ruby to test for files within it. It also uses the expect syntax, which allows for a custom error message.

control 'Test for an empty dir' do
  describe directory('/hey') do
    it 'This directory should exist and be a directory.' do
      expect(subject).to(exist)
      expect(subject).to(be_directory)
    end
  end
  if (File.exist?('/hey'))
    Array(Dir["/hey/*"]).each do |bad_file|
      describe bad_file do
        it 'This file should not be here.' do
          expect(bad_file).to(be_nil)
        end
      end
    end
  end
end

If there are files present, the resulting error message is informative:

  ×  Test for an empty dir: Directory /hey (2 failed)
     ✔  Directory /hey This directory should exist and be a directory.
     ×  /hey/test2.png This file should not be here.
     expected: nil
          got: "/hey/test2.png"
     ×  /hey/test.png This file should not be here.
     expected: nil
          got: "/hey/test.png"
james.garriss
  • 12,959
  • 7
  • 83
  • 96