Yes, what i do is, i render the nodes attributes during the report phase into a json file on disk and load it later on. For this purpose i wrote a report handler.
Handler code in a test fixture cookbook at test/fixtures/cookbooks/helper/files/default/handler/node_attrs.rb
|
|
require
'chef/handler' |
|
|
module
MyHelper |
|
|
class
NodeAttrs < Chef::Handler |
|
|
def
report |
|
|
attrs
= {
:ipaddress => @run_status.node.automatic.ipaddress, |
|
|
:fqdn =>
@run_status.node.automatic.fqdn } |
|
|
attrs
=
Chef::Mixin::DeepMerge.deep_merge(attrs, node.default) |
|
|
attrs
=
Chef::Mixin::DeepMerge.deep_merge(attrs, node.normal) |
|
|
attrs
=
Chef::Mixin::DeepMerge.deep_merge(attrs, node.override) |
|
|
|
|
|
`mkdir -p /shared` |
|
|
File.open('/shared/node.json',
'w')
do
|f| |
|
|
f.write(attrs.to_json) |
|
|
end |
|
|
|
|
|
end |
|
|
end |
|
|
End |
This handler i register in a recipe at test/fixtures/cookbooks/helper/recipes/node-attrs.rb
|
|
|
include_recipe
'chef_handler' |
|
|
|
remote_directory node['chef_handler']['handler_path']
do |
|
|
source
'handlers' |
|
|
mode
'0755' |
|
|
recursive
true |
|
|
action
:nothing |
|
|
end.run_action(:create) |
|
|
|
|
|
chef_handler
‘MyHelper::NodeAttrs'
do |
|
|
source
"#{node['chef_handler']['handler_path']}/node_attrs.rb" |
|
|
action
:nothing |
|
|
end.run_action(:enable) |
And in the Berksfile:
|
|
|
|
cookbook
‘helper',
path:
'test/fixtures/cookbooks/helper' |
|
|
End
|
Then you need a rspec helper beside your tests like this:
|
|
|
|
require
'fileutils' |
|
|
require
'json' |
|
|
|
|
|
set
:backend,
:exec |
|
|
|
|
|
@chef_node
=
nil |
|
|
|
|
|
RSpec.configure
do
|c| |
|
|
FileUtils.mkdir_p
'/shared' |
|
|
@chef_node
= ::JSON.parse(File.read('/shared/node.json'))
unless
@chef_node |
|
|
end |
In the Kitchenfile add “reicpe[helper::node-attrs]” to runlist
In your tests you can use then:
@chef_node[‘fqdn’]
for example.
If
you have a private supermarket, you can easily push a cookbook with this code and then reuse it in all your cookbooks.
Cheers
Felix
From: Prince Paulson
Date: Donnerstag, 28. Mai 2015 20:20
To: "
testing-...@googlegroups.com"
Subject: using cookbook attribute's inside serverspec testing.