【问题标题】:How can I test my LWRP with ChefSpec?如何使用 ChefSpec 测试我的 LWRP?
【发布时间】:2024-07-26 11:00:01
【问题描述】:

我创建了我的自定义 LWRP,但是当我运行 ChefSpec 单元测试时。它不知道我的 LWRP 操作。

这是我的资源

actions :install, :uninstall
default_action :install

attribute :version, :kind_of => String
attribute :options, :kind_of => String

这是我的提供者

def whyrun_supported?
  true
end

action :install do
  version = @new_resource.version
  options = @new_resource.options
  e = execute "sudo apt-get install postgresql-#{version} #{options}"
  @new_resource.updated_by_last_action(e.updated_by_last_action?)
end

这是我的 ChefSpec 单元测试:

require_relative '../spec_helper'

describe 'app_cookbook::postgresql' do

  let(:chef_run) do
    ChefSpec::Runner.new do |node|
      node.set[:app][:postgresql][:database_user] = 'test'
      node.set[:app][:postgresql][:database_password] = 'test'
      node.set[:app][:postgresql][:database_name] = 'testdb'
    end.converge(described_recipe)
  end

  it 'installs postgresql 9.1 package' do
    expect(chef_run).to run_execute('sudo apt-get install postgresql-9.1 -y --force-yes')
  end
end

这是控制台输出:

app_cookbook::postgresql

expected "execute[sudo apt-get install postgresql-9.1 -y --force-yes] with" action :run to be in Chef run. Other execute resources:

./spec/recipes/postgresql_spec.rb:23:in `block (2 levels) in <top (required)>'
  installs postgresql 9.1 package (FAILED - 1)

Failures:

  1) app_cookbook::postgresql installs postgresql 9.1 package
     Failure/Error: expect(chef_run).to run_execute('sudo apt-get install postgresql-9.1 -y --force-yes')
       expected "execute[sudo apt-get install postgresql-9.1 -y --force-yes] with" action :run to be in Chef run. Other execute resources:

     # ./spec/recipes/postgresql_spec.rb:23:in `block (2 levels) in <top (required)>'

1 example, 1 failure, 0 passed

我如何告诉 ChefSpec 使用 LWRP 操作运行测试?

【问题讨论】:

标签: unit-testing chef-infra chefspec


【解决方案1】:

您需要告诉 chefspec 进入您的资源。你可以这样做:

require_relative '../spec_helper'

describe 'app_cookbook::postgresql' do

  let(:chef_run) do
    ChefSpec::Runner.new(step_into: ['my_lwrp']) do |node|
      node.set[:app][:postgresql][:database_user] = 'test'
      node.set[:app][:postgresql][:database_password] = 'test'
      node.set[:app][:postgresql][:database_name] = 'testdb'
    end.converge(described_recipe)
  end

  it 'installs postgresql 9.1 package' do
    expect(chef_run).to run_execute('sudo apt-get install postgresql-9.1 -y --force-yes')
  end
end

您可以将 my_lwrp 替换为您想要进入的资源。

有关更多详细信息,请参阅 Chefspec 存储库自述文件中的 Testing LWRPS 部分。

【讨论】:

  • 我是否正确地说包含要测试的资源的食谱需要一个 [test] 配方来收敛,以便能够进入资源?文档对此有点粗略。
  • 你为什么使用ChefSpec::Runner而不是ChefSpec::SoloRunnerChefSpec::ServerRunner
  • ChefSpec::SoloRunner 和 ChefSpec::ServerRunner 是在提出并回答了这个问题后引入的。它们是在 ChefSpec 的 4.1.0 版本中引入的。 github.com/sethvargo/chefspec/blob/master/…
  • 如何添加平台和版本参数?例如,我尝试了 ChefSpec::SoloRunner.new(step_into: ['my_apache'], platform: 'mac_os_x', version: '10.10') 但出现错误提示“令牌 step_into 附近的语法错误”
最近更新 更多