3

I want to check, if an existing directory is empty (does not contain any files or sub-directories).

I tried the following:

describe file('/path/to/file') do
    it { should be_empty }
end

But this doesn't work. (Of course, as it is not mentioned in the docs.)

Important: I do not want to test, if the directory exists - it does exist and I can't change that.

My solution now looks as follows:

describe command('ls /data/nginx/cache/services | grep -q .') do
    its(:exit_status) { should eq 1 }
end

But thats not using the Serverspec resource type 'file'. Is there a better way to test for a folder to be empty?

René Schubert
  • 1,302
  • 2
  • 13
  • 31

1 Answers1

6

Test Glob Inside File Resource

One way to do this would be to test for an empty array when globbing the directory that should have no files in it. For example:

describe file('/path/to/dir') do
  it { should be_a_directory }
  it 'should be an empty directory' do
    Dir.glob('/path/to/dir/*').should eq []
  end
end
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • Hi Todd, I'm currently struggling with a similar issue when checking for empty directories, testing with Serverspec and the Docker backend. See https://stackoverflow.com/questions/48644823/checking-on-empty-gems-cache-fails-using-serverspec-for-docker-image-build-testi. Maybe you can help with this? Thx. – pklndnst Feb 13 '18 at 10:37