ChefSpec Ruby:如何跳过所有包含(allow_any_instance_of)但只有一个?

ChefSpec Ruby: How to skip all includes (allow_any_instance_of) but one?

我想测试一下是否执行了某个受条件限制的include。测试中不应考虑所有其他包含项,因此不应包含在内。

我要测试的文件如下所示:

include_recipe 'test::first_recipe'

if set_is_two?
   include_recipe 'test::second_recipe'
end

在我的测试中,如果函数“set_is_two”returns 为真,我想测试是否包含文件“test::second_recipe”。同时我不想在测试中包含所有其他文件,如“test::first_recipe”。

不幸的是,我目前的方法行不通。所有其他包含都被阻止,但“test::second_recipe”显然也不包含在内。

before do
    # skip all includes
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe)
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with('test::second_recipe')

    allow_any_instance_of(Chef::Recipe).to receive(:set_is_two?).and_return(true)
end

it { is_expected.to include_recipe('include_recipe::test::second_recipe') }

好像我的第一个“allow_any_instance_of”跳过了所有内容,但之后什么都没有启用。

我在这个 post

找到了问题的答案
before(:all) { @included_recipes = [] }
before do
  @stubbed_recipes = %w[test_cookbook::included_recipe apt]
  @stubbed_recipes.each do |r|
    allow_any_instance_of(Chef::Recipe).to receive(:include_recipe).with(r) do
      @included_recipes << r
    end
  end
end

it 'includes the correct recipes' do
  chef_run
  expect(@included_recipes).to match_array(@stubbed_recipes)
end

使用此示例代码,它按预期工作。