2016-01-08 24 views
0

我有一個修改DataBag值的配方,我正在爲此編寫一個測試。食譜的相關部分是:如何測試ChefSpec中的data_bag修改?

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 

兩個測試失敗,出現錯誤說「預期無匹配/合適的正則表達式/」,所以我猜測我用存根Data_Bag_Item的方式有些不對勁。從我從已發佈的代碼中刪除的其他測試中,我知道修改數據包項目的配方中的代碼實際上正在運行。

我錯過了什麼?

回答

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 
+0

感謝。像魅力一樣工作。 –

相關問題