redwolfgang20 redwolfgang20 - 2 months ago 9
Ruby Question

How to mock or stub chmod method under FileUtils class in ruby

Hi guys I really need help on how to stub or mock a chmod method under FileUtils class in ruby.

Currently I have this code.

def create_file(file)
unless File.exist?(file)
FileUtils.mkdir_p(File.dirname(file), :mode => 0755)
FileUtils.touch file
FileUtils.chmod(0644, file)
end
end


where file located under /usr/local/something_folder/filePath.fileExtension

And this is the equivalent test code I've created for that code above.

File.stub(:dirname).and_return('fileFullPath')
FileUtils.stub(:mkdir_p).and_return('fileFullPath')
FileUtils.stub(:touch).and_return('fileFullPath')
FileUtils.stub(:chmod).and_return('fileFullPath')


The problem here is the permission under /usr/local file path that's why I'm going to stub or mock that method call.

I would be glad and thankful if you can help me with this problem.

Happy coding guys :)

Answer

One rule for mocking you have to consider is "mock only what you own". File and FileUtils you don't own. If you realy want to do it you can try gem fakefs. I would recommend another approch:

class YourClass
   attr_accessor :file_class, :file_utils_class

   def file_class
      @file_class ||= File
   end

   def file_utils_class
     @file_utils_class ||= FileUtils
   end

   def create_file(file)
     unless file_class.exist?(file)
       file_utils_class.mkdir_p(file_class.dirname(file), :mode => 0755)
       file_utils_class.touch file
       file_utils_class.chmod(0644, file)
     end
   end
 end

This way you can inject an object during test that behaves like you want.