ChefSpec:如何模拟 node.chef_environment?

ChefSpec: How to mock node.chef_environment?

有谁知道如何在 chefspec 中模拟节点属性“node.chef_environment”?

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

不幸的是,通过 default_attributes 进行模拟不起作用。

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

您必须模拟 Chef's Environment class 并用它构建一个运行器。

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 是一个很好的主题讨论。