Freitag, 23. März 2012

Using vsfstream (with symfony2)

I read about vsfstream when skipping through the phpunit docs. Back then, I decided I don't need a virtual file system. Some time later, I had to test classes which read and write files and found myself creating and deleting temporary folders, messing around with nasty errors (like my favourite one where for some reasons tests fail when I don't use @runTestsInSeparateProcesses).

Install and use vsfstream

So I decided to give vsfstream a try with a new bundle I'm working on (It's about Data Migration for automated database deployment). The package itself is pretty straightforward and can be used with the pear installer (see the docs). If you want to use it with symfony2, read below on how to use it using the deps and autoloader.

To start using it, you need to put a require_once 'vfsStream/vfsStream.php'; into your testfile and then you set up a virtual dir and get the foldername for this dir:
$tmpDir = vfsStream::url('test');

Now, you can do whatever you want with this $tmpDir, using it as a string to a directory as you would with something like /home/Bob/somedir. To create a folder structure within it, you can use the create method (read the docs for more examples on this):
vfsStream::create(array('subdir' => array()));


So, here we are in 2012 and still using require_once in every (test) class we want to use vsfstream. I really hate this, so I decided to try using symfony2 deps file and the autoloader. First, register vsfstream into your deps file and install your vendors. The deps file should get this extension:

A simple php bin/vendors install will clone the repository into your vendors folder. The next step is to tell the autoloader about the new namespace:
    // ...
    'org\\bovigo\\vfs' => __DIR__.'/../vendor/vsfStream/src/main/php',

And now to use vsfstream, simply add use use org\bovigo\vfs\vfsStream; to your test class.

Another major improvement is that every installation of my project makes the relation to vsfStream clear within the deps. The common error to forget the pear installation cannot happen. When our continous integration server pulls the repository and installs the new vendors, it's all there and everything will work as on my development machine. No need to log into the server, pull the pear package and make sure it's where it should be. That's neat!

What are you waiting for?

If somebody would have told me a little bit earlier, I might have saved myself a lot of trouble. Wrestling with the file system for testing is no fun at all, and vsfstream is set up and ready to use in a matter of minutes. It's lightweight, easy and right now fills my needs perfectly. I think it's what most people need when testing interaction with the file system.

Keine Kommentare:

Kommentar veröffentlichen