rubyrspecchef-infrachefspec

How to stub_command in ChefSpec?


I have this condition in my recipe:

install_action = (::Win32::Service.exists?(windows_service['name']) ? :configure : :create)

and a ChefSpec for that in spec file:

#1: not working 
allow_any_instance_of(Win32::Service)
                .to receive(:exists?)
                .with(windows_service[:name])
                .and_return(true)
#2: also not working
stub_command("::Win32::Service.exists?(#{windows_service[:name]})").and_return(true)

Could you please help to find out what have I missed in the ChefSpec test that is not working and mocking the return value. Thanks


Solution

  • This should work:

    allow(::Win32::Service).to receive(:exists?).with(windows_service[:name]).and_return(true)
    

    Point is you stub a class method exists?, and not an instance method. That's why allow_any_instance_of does not work. And stub_command is actually for shell commands like stub_command('cat file | grep "hello"')