【问题标题】:ChefSpec testing directory existsChefSpec 测试目录存在
【发布时间】:2019-01-21 21:41:51
【问题描述】:

我正在尝试编写 ChefSpec 测试以检查配方是否仅在目录不存在时创建目录。我通过了“创建目录”的第一次测试,但第二次测试失败了。食谱在下面。有人可以帮助完成第二部分吗?因为如果目录存在,那么第一个测试就失败了。我必须删除目录才能使第一个测试通过,然后第二个测试仍然失败。

require 'spec_helper'

describe 'my_cookbook::default' do
  context 'Windows 2012' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'Windows', version: '2012')
      runner.converge(described_recipe)
    end

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

    it 'creates directory' do
      expect(chef_run).to create_directory('D:\test1\logs')
    end

    it 'checks directory' do
      expect(chef_run).to_not create_directory( ::Dir.exists?("D:\\test1\\logs") )
    end
  end
end

这是配方,它本身就可以按预期工作,但我似乎无法围绕它编写测试。

directory "D:\\test1\\logs" do
  recursive true
  action :create
  not_if { ::Dir.exists?("D:\\test1\\logs") }
end

【问题讨论】:

    标签: chef-infra chefspec


    【解决方案1】:

    not_ifonly_if是厨师guards

    然后使用保护属性告诉厨师客户端是否应该继续执行资源

    为了使用chefspec 测试您的directory resource,您必须对守卫存根,因此当chefspec 编译您的资源时,您希望not_if 守卫评估为真或假。

    为了让 ChefSpec 知道如何评估资源,我们需要告诉它如果该命令在实际机器上运行,该命令将如何返回该测试:

    describe 'something' do
      recipe do
        execute '/opt/myapp/install.sh' do
          # Check if myapp is installed and runnable.
          not_if 'myapp --version'
        end
      end
    
      before do
        # Tell ChefSpec the command would have succeeded.
        stub_command('myapp --version').and_return(true)
        # Tell ChefSpec the command would have failed.
        stub_command('myapp --version').and_return(false)
        # You can also use a regexp to stub multiple commands at once.
        stub_command(/^myapp/).and_return(false)
      end
    end
    

    【讨论】: