Search code examples
rspecchef-infrachefspec

Mocking Files during a ChefSpec run


I created a Chef resource which 'extends' the deploy resource of chef. The basic idea is to check for the existence of a file deploy/crontab similar to mechanisms deploy/after_restart.rb in the source to be deployed, and create cronjobs out of it.

While this mechanism works as it should be (see https://github.com/fh/easybib-cookbooks/blob/t/cron-tests/easybib/providers/deploy.rb#L11-L14), I am struggling with a ChefSpec based test for it. I am currently trying to create mocks using FakeFS - but when I mock the Filesystem before the Chef run, the run fails because no cookbooks are found, since they do not exist in the mocked filesystem. If I dont, the mocked file deploy/crontab is obviously not found, so the provider doesnt do anything. My current approach is to trigger FakeFS.activate! directly before runner.converge(described_recipe) in the chef_run.

I would love to hear some recommendations how to do a proper test here: Is there maybe some possiblity to enable the FakeFS only directly before the deploy-resource-run, or to mock the Filesystem only partially?


Solution

  • I had a similar problem stubbing the File system classes. The way that I have been solving this problem is as follows.

    ::File.stub(:exists?).with(anything).and_call_original
    ::File.stub(:exists?).with('/tmp/deploy/crontab').and_return true
    
    open_file = double('file')
    allow(open_file).to receive(:each_line).and_yield('line1').and_yield('line2')
    
    ::File.stub(:open).and_call_original
    ::File.stub(:open).with('/tmp/deploy/crontab').and_return open_file