我有一个修改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
这两个测试都失败了,错误说"期望nil匹配/一个合适的正则表达式/",所以我想我错误地处理了Data_Bag_Item的方式。从我已发布的代码中删除的其他测试中,我知道修改数据包项目的配方中的代码实际上正在运行。
我错过了什么?
答案 0 :(得分:1)
问题可能是ChefSpec的存根系统在返回之前将值转换为Mash,这是一个复制操作。不是从存根中返回哈希,而是使用真实的DataBagItem
实例。
还将项目放在let变量中,以便更好地确定范围:
let(:data_item) do
Chef::DataBagItem.from_hash('latest_build' => {}).tap do |item|
expect(item).to receive(:save)
end
end