为什么Chefspec找不到我的资源?

时间:2018-02-21 21:54:07

标签: chef devops chefspec

我有一个Spec配方(除此之外)测试运行两个命令之一。如果安装了第一个命令,则运行它。如果没有,那么第二个应该运行。

然而,出于某种原因,Spec配方并没有""""尽管将确切命名的资源列为"其他执行资源",但第一个执行资源。但它确实看到并传递第二个命令。

RSpec输出如下所示:

gets admin key using getkey (FAILED - 1)
gets admin key using keyremoteclient [passed]

错误消息:

Failures:

 1) cookbook-forwarders::install_forwarder_package gets admin key using getkey
 Failure/Error: expect(chef_run).to run_execute('use getkey')

   expected "execute[use getkey]" with action :run to be in Chef run. 
   Other execute resources:

   execute[use getkey]

错误的这一部分毫无意义,因为存在确切资源

    -->execute[use getkey]<--

食谱部分看起来像这样

execute 'use getkey' do
  admin_passwd = getkey((node['splunk_forwarder']['key_name']).to_s)
  user 'root'
  only_if '/usr/local/bin/inst ls getkey -noname -noversion'
end

execute 'keyremoteclient' do
  admin_passwd = keyremoteclient((node['splunk_forwarder']['key_kgp']).to_s, (node['splunk_forwarder']['key_name']).to_s)
  user 'root'
  not_if '/usr/local/bin/inst ls getkey -noname -noversion'
end

我在'only_if&#39;中删除了命令。在Spec配方的开头守护:

  before do
    # stub command to get admin password using getkey
    stub_command('getkey(the_key_name)').and_return('xyz')
    # stub command to get admin password using keyremoteclient
    stub_command('keyremoteclient(the_kgp, the_key_name)').and_return('xyz')
    # stub check if getkey is installed
    stub_command('/usr/local/bin/inst ls getkey -noname -noversion').and_return(true)
    # stub check for already installed getkey package to use keyremoteclient
    stub_command('/usr/local/bin/inst ls getkey -noname -noversion').and_return(false)
end

Spec配方部分如下所示:

it 'gets admin key using ykeykeygetkey' do
  expect(chef_run).to run_execute('use getkey')
end

it 'gets admin key using ykeykeyremoteclient' do
  expect(chef_run).to run_execute('keyremoteclient')
end

1 个答案:

答案 0 :(得分:1)

所以有一些问题;一,你不能使用stub_command来存储像getkey()这样的Ruby代码。其次,您对两个警卫使用相同的命令,因此存根可能存在冲突。我建议将代码重构为仅使用单个命令执行。您可能不需要为此编写单元测试,只需编写集成测试。