I'm a Floridian web engineer who planted his roots in Paris. Some of my favorite past-times are analyzing and optimizing development processes, building solid APIs, mentoring junior devs, and long walks on the beach.

Testing File operations

I've recently been working on a gem that will integrate git and pivotal into my current command-line workflow. I'll talk more about that in a future post, but check it out if you're interested. As I've been working on it, I have become increasingly aware how awesome mocking and stubbing are. I've been using mocha(gem install mocha #bros) for all of my needs and after a little playing around it has made me a very happy person. I haven't had much use for either until this gem I've been working on. The gem does more file operations that I normally do since most web stuff is heavier on the db action.

On this project I ran into an issue where I wasn't sure how to test the following code.

def load_project_id
  File.open('.git/config') do |file| 
    file.each_line do |line| 
      if line.slice('[pivotal]')
        return file.gets.tr("\s\t\n",'').split(' = ').last

For this chunk of code, I wanted to spoof the variable 'file' so that I could make sure that everything in the File.open block does what it needs to. At first I thought that there might be a way to stub the variable that comes in to the block, but it ends up there is a more straight forward thing to do. I ended up turning File.open(".git/config") into File.open(git_config) where git_config is a method that determines the git config directory based on the current working directory. This way I can test this method by stubbing the git_config method with some file I've put in the /tmp directory and keep my config files clean.