michaelprog
michaelprog

Reputation: 45

How can I mock the creation of directory in rspec?

This is the method that creates a directory.

def create_directory(path)
   system 'mkdir', '-p', path
end

I created an rspec for this method and used fakefs to mock the creation of directory.

it 'should create directory given path as parameter' do
     FakeFS do
       create_directory(DIRECTORY_PATH)
     end
     expect(File.exists?(DIRECTORY_PATH)).to be_truthy
end

When I execute the rspec command, I got this error.

    Failures:

      1) common Test for common method use should create file given file as parameter
         Failure/Error: expect(File.exists?(DIRECTORY_PATH)).to be_truthy

           expected: truthy value
                got: false
         # ./spec/unit/lib/common_spec.rb:16:in `block (3 levels) in <top (required)>'

    Finished in 0.01474 seconds (files took 0.10763 seconds to load)
    2 examples, 1 failure

    Failed examples:

    rspec ./spec/unit/lib/common_spec.rb:12 # common Test for common method use should create file given file as parameter

How to mock the creation of directory using rspec or fakefs?

Upvotes: 3

Views: 1639

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

  1. Use ruby tools for creating directory instead of shelling out.
  2. Move your expectation into the fakefs block.

Upvotes: 3

Related Questions