如何使用ChefSpec测试我的LWRP?

Rob*_*ert 6 unit-testing chef-infra chefspec

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

这是我的资源:

actions :install, :uninstall
default_action :install

attribute :version, :kind_of => String
attribute :options, :kind_of => String
Run Code Online (Sandbox Code Playgroud)

这是我的提供者:

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
Run Code Online (Sandbox Code Playgroud)

这是我的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
Run Code Online (Sandbox Code Playgroud)

这是控制台输出:

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
Run Code Online (Sandbox Code Playgroud)

我怎么能对使用LWRP操作运行测试的ChefSpec说?

pun*_*kle 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
Run Code Online (Sandbox Code Playgroud)

您可以将my_lwrp替换为要插入的资源.

有关更多详细信息,请参阅Chefspec repo自述文件中的测试LWRPS部分.