Mocking out a class in Chefspec

Hi, we’re trying to mock out citadel in chefspec but aren’t getting anywhere.
Here’s what we have so in our spec file:

before do
require File.join(RSpec.configuration.cookbook_path, ‘/’,
‘citadel/libraries/default.rb’)
allow_any_instance_of(Citadel).to
receive(:[]).with(‘development/celery__result_db_username’).and_return(‘fakeusername’)
allow_any_instance_of(Citadel).to
receive(:[]).with(‘development/celery__result_db_password’).and_return(‘fakepassword’)
end

This seems to import citadel, but then the mocks are never called.

FYI here’s a link to citadel repo https://github.com/poise/citadel

Thanks!
Alex

On Wed, Nov 12, 2014 at 02:03:13PM -0800, alex.makkaveyev@essess.com wrote:

Hi, we're trying to mock out citadel in chefspec but aren't getting anywhere.
Here's what we have so in our spec file:

before do
require File.join(RSpec.configuration.cookbook_path, '/',
'citadel/libraries/default.rb')
allow_any_instance_of(Citadel).to
receive(:).with('development/celery__result_db_username').and_return('fakeusername')
allow_any_instance_of(Citadel).to
receive(:).with('development/celery__result_db_password').and_return('fakepassword')
end

This seems to import citadel, but then the mocks are never called.

That's because when you run ChefSpec::*Runner#converge all the chef libraries/
classes are loaded again and the Citadel mocks are overridden. I mean,
#chef_run reloads all the cookbook library directories.

I do not know a simple solution.

Maybe you could create a mockable Citadel subclass of your library class and
mock it.

Something like:

class MyLibraryClass
class Citadel << ::Citadel
end
end

describe MyLibraryClass do
before do
allow_any_instance_of(::MyLibraryClass::Citadel) ...
end
end

This is assuming you're using a class. If you are calling Citadel from a Recipe,
you could try creating a Citadel subclass of the Recipe class:

class Chef::Recipe
class Citadel << ::Citadel
end
end

The same for providers.

I have not tried any of this but it might work.

--
Xabier de Zuazo