[rspec-users] testing Rake tasks with FakeFS

Ben Mabey ben at benmabey.com
Mon Nov 2 01:17:16 EST 2009

Jake Benilov wrote:
> Hello Ben,

Hi Jake,
I hope you don't mind but I am copying this response to the rspec-users 
list in case any one else is able to shed more light on it.
> I have a bit of a newbie question regarding fakefs; I want to test Rake
> tasks using fakefs and rspec:
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> require 'fakefs/safe'
> require 'rake'
> require 'spec'
> task :create_file do
>   touch "/abc"
> end
> describe "my rake script" do
>   before do
>     FakeFS.activate!
>   end
>   it "should create a file abc" do
>     Rake::Task[:create_file].invoke
>     File.should exist("/abc")
>   end
>   after do
>     FakeFS::FileSystem.clear
>     FakeFS.deactivate!
>   end
> end
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> When I run this, a real file /abc is being created on the filesystem. I
> am guessing that this has to do with the fact that the touch method
> isn't FileUtils.touch, but rather that FileUtils is being included into
> Rake and thus touch is not being mocked out.
> Is my analysis correct? In any case, is there a way that you can think
> of to write such a spec?

I've never tested a Rake task with FakeFS before so I looked into a 
bit.  In short, I think your analysis is correct.  However, it is a bit 
confusing because Rake does in fact use FileUtils::touch.  I discovered 
that when you fully qualify FileUtils::touch in the rake task then it 
works fine.  I stepped into rake's call to 'touch' and it seems to be 
doing some other logic specific to rake.  My hunch is that rake somehow 
retains a handle onto the original FileUtils const even though it is 
replaced by the fake ones with FakeFS.  I'm not familiar with Rake's 
code base so I can't say that for sure or how to really fix it.  
However, you can fully qualify the call if you want to but that will be 
going around some rake logic and may have some undesired effects (I 
can't think of what though).  I'm sure someone more familiar with Rake's 
code could offer a better solution.  Here is a gist of my explorations 
in case anyone else wants to play around with it:



More information about the rspec-users mailing list