1

Does anyone know how to mock the node attribute "node.chef_environment" in chefspec?

template 'my_script.sh' do
 source 'my_script.erb'
 variables(
  environment: node.chef_environment
 )
end

Unfortunately, mocking via default_attributes does not work.

describe "my_test" do
  context "create template file" do 
     default_attributes['chef_environment']= 'my_env'
     it { is_expected.to render_file('my_script.sh').with_content('env=my_env')}
  end
end
user5580578
  • 1,134
  • 1
  • 12
  • 28

1 Answers1

2

You have to mock out Chef's Environment class and construct a runner with it.

cached(:chef_run) do
  ChefSpec::SoloRunner.new do |node|
    env = Chef::Environment.new
    env.name 'my-fake-env'
    allow(node).to receive(:chef_environment).and_return(env.name)
    allow(Chef::Environment).to receive(:load).and_return(env)
  end.converge(described_recipe)
end

Here is a good discussion on the topic.

Andy Foster
  • 237
  • 2
  • 11