存根node.attribute?主要规格

stub node.attribute? in chefspec

我正在尝试为以下配方代码创建规范测试:

    if node.attribute?(node['tested_cookbook']['some_attribute'])
       include_recipe('tested_cookbook::first')
    else
       include_recipe('tested_cookbook::second')

我对此有以下规范:

    require 'spec_helper'

    describe 'tested_cookbook::default' do

    let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'windows', version: '2008R2') do |node|
    node.set['tested_cookbook']['some_attribute'] = "some_value"
    end.converge(described_recipe) }

      it 'includes recipe iis' do
         expect(chef_run).to include_recipe('tested_cookbook::first')
      end
    end

问题是这个测试总是会失败。 如何正确模拟 'node.attribute?' 的结果? 谢谢你。

我不确定您是否可以在不使用猴子补丁的情况下覆盖 Chefspec 中的节点对象,我认为这可能比它的价值更麻烦。我几乎从未见过 node.attribute? 被使用过,所以它可能有点反模式。 (你真的关心如果它被设置了,还是它是否有一个非零值?)

我会首先避免使用 attribute?,例如

食谱:

if node['tested_cookbook'] && node['tested_cookbook']['some_attribute'])
   include_recipe('tested_cookbook::first')
else
   include_recipe('tested_cookbook::second')
end

规格:

require 'spec_helper'

describe 'tested_cookbook::default' do

let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'windows', version: '2008R2') do |node|
node.set['tested_cookbook']['some_attribute'] = "some_value"
end.converge(described_recipe) }

  it 'includes recipe iis' do
     expect(chef_run).to include_recipe('tested_cookbook::first')
  end
end

给这些属性一个默认值也是很常见的做法,所以更习惯地说:

attributes/default.rb:

default['tested_cookbook']['some_attribute'] = 'second'

食谱:

include_recipe "tested_cookbook::#{node['tested_cookbook']['some_attribute']}"

然后在您的规范中,进行与之前相同的检查。您正在使用 运行 ::second 的属性,但允许其他人将其覆盖为 ::first。如果您不喜欢实际使用属性值来包含的模式,您可以将其作为一个标志并保留您之前的 if 语句。