如何使用file_cache_path测试chef资源

时间:2018-04-13 08:29:09

标签: chef chef-recipe

我的食谱中有以下资源

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]

任何人都可以帮助您测试这种情况吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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