Unit testing stub node.attribute?切夫斯佩克

Unit testing stub node.attribute?切夫斯佩克,unit-testing,chef-infra,cookbook,chefspec,Unit Testing,Chef Infra,Cookbook,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

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

    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对象,我认为这可能比它的价值更麻烦。我几乎从来没有看到使用过
node.attribute?
,所以它可能有点反模式。(您真的在乎它是否被设置,而不是它是否具有非零值?)

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

配方:

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

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

attributes/default.rb:

default['tested_cookbook']['some_attribute'] = 'second'
配方:

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

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

我不确定您是否可以在不使用猴子补丁的情况下覆盖Chefspec中的节点对象,我认为这可能比它的价值更麻烦。我几乎从来没有看到使用过
node.attribute?
,所以它可能有点反模式。(您真的在乎它是否被设置,而不是它是否具有非零值?)

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

配方:

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

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

attributes/default.rb:

default['tested_cookbook']['some_attribute'] = 'second'
配方:

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

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

谢谢Martin,我们已经搬走了,在配方中使用了不同的方法,因此不再需要担心。谢谢Martin,我们已经搬走了,在我们的食谱中使用了不同的方法,所以这不再是一个问题。