Mocking files while running ChefSpec

I created a chef resource that "extends" the chef's deployment resource. The main idea is to check for the existence of a file deploy/crontabsimilar to the mechanisms deploy/after_restart.rbin the source that will be deployed and create cronjobs from it.

Although this mechanism works as it should (see https://github.com/fh/easybib-cookbooks/blob/t/cron-tests/easybib/providers/deploy.rb#L11-L14 ), I'm struggling with ChefSpec based testing. I am currently trying to create mocks with FakeFS- but when I make fun of the file system before running Chef, the launch fails because cookies are not found because they do not exist on the manufactured file system. If I do not, then the finished file is deploy/crontabclearly not found, so the provider does nothing. My current approach is to call FakeFS.activate!immediately before runner.converge(described_recipe)in chef_run.

I would like to hear some recommendations on how to do the right test here: is it possible that it is possible to enable FakeFS just before deploying the resource or partially mock the file system?

+4
source share
2 answers

I had a similar problem with file system classes. The way to solve 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
+4
source

Since punkle solutions are syntactically outdated and some parts are missing, I will try to give a new solution:

require 'spec_helper'

describe 'cookbook::recipe' do

  let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) }


  file_content = <<-EOF
...here goes your
multiline
file content
EOF

  describe 'describe what your recipe should do' do

    before(:each) do
      allow(File).to receive(:exists?).with(anything).and_call_original
      allow(File).to receive(:exists?).with('/path/to/file/that/should/exist').and_return true
      allow(File).to receive(:read).with(anything).and_call_original
      allow(File).to receive(:read).with('/path/to/file/that/should/exist').and_return file_content
    end

    it 'describe what should happen with the file...' do
      expect(chef_run).to #...
    end
  end

end
+3
source

Source: https://habr.com/ru/post/1533189/


All Articles