如何使用ChefSpec测试我的LWRP?

时间:2014-03-21 15:01:51

标签: unit-testing chef chefspec

我创建了自定义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

如何通过LWRP操作运行测试的ChefSpec?

1 个答案:

答案 0 :(得分:13)

您需要告诉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 repo自述文件中的Testing LWRPS部分。