When you write serverspec integration tests, it would be great to have access to chef attributes of cookbook that you’re testing.
There’s a fast and simple way to do this.
name 'test-helper'
maintainer 'John Smith'
maintainer_email 'john@example.com'
license 'Apache 2.0'
description 'Dumps chef node data to json file'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.0.1'
recipe 'default', 'Dumps chef node data to json file'
%w{ ubuntu debian }.each do |os|
supports os
end
require 'serverspec'
require 'pathname'
require 'net/http'
require 'net/smtp'
require 'json'
include Serverspec::Helper::Exec
include Serverspec::Helper::DetectOS
RSpec.configure do |c|
c.before :all do
c.os = backend(Serverspec::Commands::Base).check_os
end
end
$node = ::JSON.parse(File.read('/tmp/serverspec/node.json'))
Use chef attributes in tests
12345678910111213
require 'spec_helper'
describe 'my_cookbook' do
context 'dependencies recipe. It' do
$node['backup']['dependencies'].each do |bgem|
it "installs backup gem dependency: #{bgem[0]}" do
expect(package bgem[0]).to be_installed.by('gem')
end
end
end
end
Conclusion
if you execute:
1
kitchen verify
you should see:
1234
my_cookbook
dependencies recipe. It
installs backup gem dependency: fog
installs backup gem dependency: aws-s3