【问题标题】:ChefSpec unable to find cookbookChefSpec 找不到食谱
【发布时间】:2016-03-01 14:00:20
【问题描述】:

当我运行我的单元测试用例(用 ChefSpec 编写)时,我收到以下错误:

Chef::Exceptions::CookbookNotFound:未找到 Cookbook azuredns。如果 您正在从另一本烹饪书中加载 azuredns,请确保您 在元数据中配置依赖项

以下是我的规范文件、配方文件和元数据文件

azurens/spec/get_azure_token_spec.rb

require 'chefspec'
require 'rest-client'

describe 'azuredns::get_azure_token' do
  let(:chef_run) do
    # Step into the provider
    runner = ChefSpec::SoloRunner.new(step_into: ['azuredns_token'])
    # Read test data from a json file
    file_path = File.expand_path('test_data.json', __dir__)
    file = File.open(file_path)
    contents = file.read
    node_attr = JSON.parse(contents)
    # Load test data into node object
    runner.node.consume_attributes(node_attr)
    runner.converge(described_recipe)
  end

  before(:each) do
    # Mock post method of RestClient
    allow(RestClient).to receive(:post)
      .and_return({ access_token: 'i-am-a-token' }.to_json)
  end

  it 'retrieves token' do
    expect(chef_run).to retrieve_azuredns_token('azure_token')
  end

  it 'varifies the expected value of azure_rest_token' do
    expect(chef_run.node['azure_rest_token']).to eq('Bearer i-am-a-token')
  end

  it 'does not retrieve token due to incorrect resource name' do
    expect(chef_run).to_not retrieve_azuredns_token('azure_token1')
  end

  it 'raises exception due to error in response' do
    # Mock post method of RestClient
    allow(RestClient).to receive(:post)
      .and_return({ error: 'invalid_grant' }.to_json)
    expect { chef_run }.to raise_error(Exception)
  end
end

azurens/recipe/get_azure_token.rb

require 'rest_client'
require 'json'

cloud_name = node['workorder']['cloud']['ciName']
cloud = node['workorder']['services']['dns'][cloud_name]
dns_attributes = cloud['ciAttributes']

#  Establish connection and get a security token
token = azuredns_token 'azure_token' do
  tenant_id dns_attributes['tenant_id']
  client_id dns_attributes['client_id']
  client_secret dns_attributes['client_secret']
end

token.run_action(:retrieve)

azuredns/metadata.rb

name             'Azuredns'
maintainer       'Shaffan'
maintainer_email 'shaffan.chaudhry1@gmail.com'
license          'Apache License, Version 2.0'
description      'Installs/Configures Azure DNS'
version          '0.1.0'
depends          'azure'

请帮忙!

【问题讨论】:

    标签: ruby unit-testing chef-infra chef-recipe chefspec


    【解决方案1】:

    Azuredns != azuredns :-)

    修复元数据中的名称。 Chef 以及 UNIX 世界中的几乎所有内容都区分大小写。

    【讨论】:

    • 这是我们保持首字母大写的编码约定。
    • 当我像这样更改我的测试用例时:描述“Azuredns::get_azure_token”我收到此错误:“get_azure_token.rb 配方中没有资源或方法 azuredns_token”也就是说,它无法找到我的自定义资源(LWRP)
    • 是的,因为您必须再次使用Azuredns_tokenall 区分大小写,这就是您应该改正名称的原因。
    • 我真的不知道为什么我们甚至允许在食谱名称中使用大写字母,我们可能应该停止这样做。
    • 再一次,你的标准是错误的,你正在解决错误的问题。以后你会遇到更多这样的问题。