Having an issue with stabbing of the chef_env variable in my spec tests. Part of recipe:
recipe.rb
example_credentials = data_bag_item(:credentials, 'example')
template '/etc/nginx/sites-available/example.conf' do
source 'http/example.conf.erb'
owner 'root'
group 'root'
mode '0644'
variables({
authorization: Base64.strict_encode64(example_credentials[node.chef_environment]['example_auth']),
cluster_id: node['project']['http']['example']['cluster_id']
})
end
Test for it:
test.rb
require 'spec_helper'
describe 'project::http' do
let(:chef_run) do
ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '16.04') do |node|
env = Chef::Environment.new
env.name 'test'
expect(node).to receive(:chef_environment).and_return env.name
expect(Chef::Environment).to receive(:load).and_return env
end.converge(described_recipe)
end
before(:each) do
stub_data_bag_item(:credentials, 'example').and_return(example_auth: 'test_value')
end
end
However I still catch an error.
expected no Exception, got #<NoMethodError: undefined method `[]' for nil:NilClass> with backtrace
This error is often raised, when you try to access your Hash nested attributes, but there is no parent attribute that your are looking for.
In your case you stub the credentials data bag and it returns a hash:
{
example_auth: 'test_value'
}
Then in this line:
authorization: Base64.strict_encode64(example_credentials[node.chef_environment]['example_auth']),
You are trying to access "test" key (= node.chef_environment) of the hash, but it is not there. You need to change your stubbed data bag, so it has "test" key also.
stub_data_bag_item(:credentials, 'example').and_return(
{
'test' => {
'example_auth' => 'test_value'
}
}
)