如何使用 file_cache_path 测试 Chef 资源

How to test chef resource using file_cache_path

我的食谱中有以下资源

download_dir = "#{Chef::Config[:file_cache_path]}\BESClient"
task_done = "#{Chef::Config[:file_cache_path]}\BESClient\installed.txt"

file task_done do
  content Date.today.to_s
  action :create_if_missing
end

对应的我写了下面的厨师规范测试

    context 'Windows 2012R2: when all attributes are default' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'windows', version: '2012R2', file_cache_path: 'C:\Program Files (x86)\BigFix Enterprise')
      runner.converge(described_recipe)
    end

    it 'converges successfully' do
      expect { chef_run }.to_not raise_error
    end

    download_dir = 'C:\Program Files (x86)\BigFix Enterprise\BESClient'
    task_done = 'C:\Program Files (x86)\BigFix Enterprise\BESClient\installed.txt'

    it 'creates a file with attributes' do
       expect(chef_run).to create_file_if_missing(task_done.to_s).with(
         content: Date.today.to_s)
    end

这会尝试在我的工作站上创建 C:\Program Files (x86)\BigFix Enterprise 目录,但如果我从 Runner 中删除 file_cache_path 变量,单元测试将失败并出现以下错误

  1) besclient::windows Windows 2012R2: when all attributes are default creates
a file with attributes
     Failure/Error:
       expect(chef_run).to create_file_if_missing(task_done.to_s).with(
         content: Date.today.to_s
       )

       expected "file[C:\Program Files (x86)\BigFix Enterprise\BESClient\install
ed.txt]" with action :create_if_missing to be in Chef run. Other file resources:


         file[C:/Users/AKANKS~1/AppData/Local/Temp/chefspec20180413-11784-1dp9wh
rfile_cache_path\BESClient\installed.txt]

有人帮忙测试这个场景吗?

默认情况下,chefspec 为每个 运行 中的文件缓存设置一个新的临时目录,您的机器中可能不存在该目录。为了避免这种情况,我们需要设置 file_cache_path。除非指定,否则您的规格测试将失败。您可以在 spec_helper.rb 文件中设置此项以避免在每个规范文件中重复

RSpec.configure do |config|
  config.file_cache_path = Chef::Config[:file_cache_path]
end

只需在规范中使用 Chef::Config[:file_cache_path]。这通常不是一个好主意(使用相同的值作为输入和测试),但在这种情况下,它非常简单,值得这样做。

expect(chef_run).to create_file_if_missing("#{Chef::Config[:file_cache_path]}\BESClient\installed.txt")