Using FakeFS with Cucumber features

06 October 2009 Using FakeFS with Cucumber features

For a little Ruby library I'm currently working on, I decided to use "Cucumber": to spec out the library features. The library itself interacts heavily with the file system which has traditionally been a pain to test, requiring stubbing in various places that would inevitably lead to tight coupling between tests and implementation. Enter "FakeFS":, a great little gem that makes testing the file system a breeze. It essentially acts as a drop-in in-memory file system for your tests but more than that, Ruby's built-in libraries (File, FileUtils, Dir etc.) just work as you would expect them to, except they interact with FileFS instead of the actual file system. See the README for more information. To use this with Cucumber, you need to be aware that you cannot just require the fakefs gem in your Cucumber env.rb - doing so would break Cucumber as it would be unable to find your step definitions and other files as I quickly found out. Neither can you just require it in the step definition files as the fake file system would not be cleaned up between scenarios leading to unpredictable results. What you need to do instead is use the "built-in Cucumber hooks": and take advantage of the FakeFS "safe mode" to enable and disable FakeFS between scenarios. In addition, you'll want to clear the fake file system as simply disabling FakeFS does not do this automatically. Simply add the following code to your @features/support/env.rb@ file:
require 'fakefs/safe'

Before do

After do
And that's it - you are now good to go with your Cucumber features. Write steps that interact with the file system without leaving a single trace on your physical file system.