如何在 ChefSpec 中测试 data_bag 修改?

How can I test for data_bag modifications in ChefSpec?

我有一个修改 DataBag 值的方法,我正在尝试为此编写一个测试。食谱的相关部分是:

def get_deployment_data(data_bag_name)
  data_bag_item(data_bag_name, 'deployment')
end

# Update master data bag
master_deployment_data = get_deployment_data(node['data_bag']['master'])
master_deployment_data['latest_build']['number'] = latest_build_number
master_deployment_data['latest_build']['packages_path'] = latest_packages_path
master_deployment_data.save

测试看起来像这样:

require 'spec_helper'

describe 'my_cookbook::configure_deployment' do
  let(:chef_runner) do
    ChefSpec::SoloRunner.new
  end

  let(:chef_node) do
    chef_runner.node
  end

  let(:chef_run) do
    chef_runner.converge(described_recipe)
  end

  context 'When all attributes are default' do
# snip #
    context 'in a specified environment' do
# snip #
      context 'with an assigned role' do
# snip #
        context 'equal to the deployment master role' do
          data_item = { 'latest_build' => {} }

          before do
            stub_data_bag_item('my_data_bag', 'deployment').and_return(data_item)
            allow_any_instance_of(Hash).to receive('save')
            chef_run
          end

# snip #

          it 'sets the master data bag build number correctly' do
            expect(data_item['latest_build']['number']).to match(/an appropriate regex/)
          end

          it 'sets the master data bag packages path correctly' do
            expect(data_item['latest_build']['packages_path'])
              .to match(/an appropriate regex/)
          end
        end
      end
    end
  end
end

两个测试都失败了,并显示 "expected nil to match /an appropriate regex/" 错误,所以我猜我对 Data_Bag_Item 进行存根的方式有问题。从我从发布的代码中删除的其他测试中,我知道修改数据包项的配方中的代码实际上是 运行.

我错过了什么?

问题可能是ChefSpec的存根系统在返回之前将值转换为Mash,这是一个复制操作。不要从存根返回哈希,而是使用真实的 DataBagItem 实例。

还将项目放在 let 变量中,以便更好地限定范围:

let(:data_item) do
  Chef::DataBagItem.from_hash('latest_build' => {}).tap do |item|
    expect(item).to receive(:save)
  end
end