0

I would like to test whether a certain include which is subject to conditions is being executed. All other includes should not be taken into account in the test and therefore should not be included.

My file that I want to test looks like this:

include_recipe 'test::first_recipe'

if set_is_two?
   include_recipe 'test::second_recipe'
end

In my test I want to test that the file "test::second_recipe" is included if the function "set_is_two" returns true. At the same time I don't want to have to include all other files like "test::first_recipe" in the test.

Unfortunately, my current approach does not work. All other includes are prevented, but the "test::second_recipe" is apparently not included as well.

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') }

It seems as if my first "allow_any_instance_of" skips everything, but nothing is enabled afterwards.

user5580578
  • 1,134
  • 1
  • 12
  • 28
  • What is `include_recipe`? After some googling, my guess it's a method coming from [the `chefspec` gem](https://github.com/chefspec/chefspec)? And, what is the `subject` in your test? I'm guessing it's an instance of the class containing your fist code snippet? – Tom Lord Jul 30 '21 at 20:48
  • My guess is that these stubs don't really make sense; you can't stub out the actual inclusion of a recipe and then simultaneously expect a test to pass that's looking for the inclusion? – Tom Lord Jul 30 '21 at 20:49
  • Ideally I'd probably just get rid of these `allow_any_instance_of` declarations. Or failing that, if it's not possible, my guess is that you'd need to write this test differently -- for example, perhaps something like: `is_expected.to have_received(:include_recipe).with('test::second_recipe')`. – Tom Lord Jul 30 '21 at 20:50

1 Answers1

0

I found the answer to my problem at this 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

Using this example code, it is working as expected.

user5580578
  • 1,134
  • 1
  • 12
  • 28