【问题标题】:File names in Chef InSpecChef InSpec 中的文件名
【发布时间】:2016-12-09 01:34:57
【问题描述】:

在 Ruby 中,* 用于表示文件名。

例如,/home/user/*.rb 将返回所有以.rb 结尾的文件。我想在 Chef InSpec 中做类似的事情。

例如:

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

它应该给我/home/user 目录中的所有文件,并检查该目录中是否存在任何文件。换句话说,我想在 Chef 中检查这个目录是否为空。

我该怎么做?

【问题讨论】:

    标签: ruby chef-infra inspec


    【解决方案1】:

    * 用于 glob 主要是一个 shell 功能,正如您所料,file 资源不支持它们。请改用command 资源:

    describe command('ls /home/user') do
      its(:stdout) { is_expected.to eq "\n" }
    end
    

    【讨论】:

    • 你能告诉我这个语法its(:stdout) { is_expected.to eq "\n" }。它不是 InSpec 大厨,is_expected 的资源是什么?
    • 这是 RSpec 本身的语法和 rspec-its gem 的混合。两者都不是 InSpec 特有的。相当于it { expect(subject.stdout).to eq "\n" },只是打字少了一点,句子的可读性更高了。
    【解决方案2】:

    这是另一种测试目录是否存在的方法,如果存在,它使用 Ruby 来测试其中的文件。它还使用expect 语法,允许自定义错误消息。

    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
    

    如果存在文件,则生成的错误消息会提供信息:

      ×  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"
    

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2022-11-11
      • 2016-12-15
      • 2017-01-27
      • 2018-03-30
      • 2021-09-29
      • 1970-01-01
      • 2018-01-12
      • 2018-04-22
      相关资源
      最近更新 更多