0

我有一个 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

我在 Spec 配方开头的 'only_if' 守卫中删除了命令:

  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
4

1 回答 1

1

所以有几个问题;一,你不能使用 stub_command 来存根 Ruby 代码,比如getkey(). 其次,您对两个守卫使用相同的命令,因此存根可能会发生冲突。我建议重构您的代码以仅使用单个命令执行。您可能不需要为此编写单元测试,只需编写集成测试即可。

于 2018-02-21T22:25:47.090 回答