【问题标题】:stub_command with node attribute variables带有节点属性变量的 stub_command
【发布时间】:2018-06-11 18:24:55
【问题描述】:

我用谷歌搜索了一下,似乎可以做到,但显然我做错了。

所以我正在尝试运行powershell_script 的这个 sn-p:

powershell_script 'Unzip' do
  code <<-EOH
  Expand-Archive -Path 'E:\\apache-tomee-1.7.4-plus.zip' -DestinationPath "E:\\#{node['COOKBOOK']['Product']}-#{node['COOKBOOK']['Region']}-" + count.to_s.rjust(2, "0")"
  EOH
  guard_interpreter :powershell_script
  not_if "Test-Path -Path E:\\#{node['COOKBOOK']['Product']}-#{node['COOKBOOK']['Region']}-01"
end

现在这些节点属性在属性 default.rb 中设置

default['COOKBOOK']['Product'] = 'product'
default['COOKBOOK']['Region'] = 'region'

我在从那里获取到规范文件中应该包含的内容时遇到了问题。

require 'spec_helper'
describe 'COOKBOOK::default' do
  context 'when all attributes are default, on Windows 2012R2' do
    let(:chef_run) do
      # for a complete list of available platforms and versions see:
      # https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
      runner = ChefSpec::ServerRunner.new(platform: 'windows', version: '2012R2')
      runner.converge(described_recipe)
    end
    it 'converges successfully' do
      stub_command('Test-Path -Path E:\\#{node['COOKBOOK']['Product']}-#{node['COOKBOOK']['Region']}-01').and_return(true)
      expect { chef_run }.to_not raise_error
    end
  end
end

谁能帮帮我?

提前致谢。

【问题讨论】:

  • 您遇到错误了吗?究竟是什么问题?

标签: chef-infra chefspec


【解决方案1】:

首先,stub_command 行有问题。您将行用单引号括起来,因此这些属性插值不起作用,所以用双引号括起来:

stub_command("Test-Path -Path E:\\#{node['COOKBOOK']['Product']}-#{node['COOKBOOK']['Region']}-01").and_return(true)

现在你会得到这个错误:

 NameError:
   undefined local variable or method `node' for #<RSpec::ExampleGroups::ExampleSoDefault::WhenAllAttributesAreDefaultOnWindows2012R2:0x0000000004066720>

您的节点属性在您的 rspec 测试中不可用。此外,rspec 会识别您的 not_if,并使用已替换的属性,如下所示:

not_if "Test-Path -Path E:\\product-region-01"

所以你需要存根该命令,如下所示:

require 'spec_helper'
describe 'example-so::default' do
  context 'when all attributes are default, on Windows 2012R2' do
    let(:chef_run) do
      # for a complete list of available platforms and versions see:
      # https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
      runner = ChefSpec::ServerRunner.new(platform: 'windows', version: '2012R2')
      runner.converge(described_recipe)
    end
    it 'converges successfully' do
      stub_command('Test-Path -Path E:\\product-region-01').and_return(true)
      expect { chef_run }.to_not raise_error
    end
  end
end

如果您需要测试多个不同的属性设置,您可以适当地set attributes 并针对每组条件运行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    相关资源
    最近更新 更多