简体   繁体   English

ChefSpec测试目录存在

[英]ChefSpec testing directory exists

I am trying to write a ChefSpec test to check that the recipe creates a directory only if it doesn't exist. 我正在尝试编写ChefSpec测试,以检查配方是否仅在目录不存在时才创建目录。 I get my first test of "creating directory" pass but the second test fails. 我通过了“创建目录”的第一个测试,但第二个测试失败了。 The recipe is down below. 食谱如下。 Can someone please help in getting the second part right? 有人可以帮忙完成第二部分吗? Because if the directory exists, then the first test fails. 因为如果目录存在,则第一次测试将失败。 I have to delete the directory to make the first test pass and then the second test fails anyway. 我必须删除目录才能进行第一次测试,然后第二次测试仍然失败。

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

Here is the recipe, which on its own works as intended but I cant seem to write a test around it. 这是食谱,它可以按预期的方式工作,但是我似乎无法围绕它编写测试。

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

not_if or only_if are chef guards : not_ifonly_if是厨师守卫

a guard property is then used to tell the chef-client if it should continue executing a resource 然后使用保护属性来告知厨师客户端是否应继续执行资源

in order to test your directory resource with chefspec , you will have to stub the guard so when chefspec compiles your resources you want the not_if guard to evaluates to either true or false. 为了使用chefspec测试directory资源 ,您将必须对guard进行存根(stub),以便chefspec编译您的资源时,您希望not_if Guard的评估结果为true或false。

In order for ChefSpec to know how to evaluate the resource, we need to tell it how the command would have returned for this test if it was running on the actual machine: 为了让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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM