tags:

views:

58

answers:

2

I'm used to making calls such as:

new_count.should eql(10)

on variables, but how can I do something similar with a class method such as File.directory?(my_path)?

Every combination of File.should be_directory(my_path) that I've tried leads to a method missing, as Ruby tries to find "be_directory" on my current object, rather than matching it against File.

I know I can turn it around and write

File.directory?(my_path).should == true

but that gives a really poor message when it fails.

Any ideas?

A: 

Hmm, maybe I have an idea.

File is part of Ruby proper, so it may have elements written in C. Some of Ruby's meta-programming tools break down when dealing with classes imported from C, that could explain Rspec's failure to make .should behave as expected.

If that's true, there is no real solution here. I'd suggest using the MockFS library:

This downside to MockFS is using it everywhere you'd normally use File, Dir and FileUtils:

require 'mockfs'

def move_log
  MockFS.file_utils.mv( '/var/log/httpd/access_log', '/home/francis/logs/' )
end

The upside, especially if your code is file-intensive, is the ability to spec really complex scenarios out, and have them run without actually touching the slow filesystem. Everything happens in memory. Faster, more complete specs.

Hope this helps, Good luck!

mixonic
A: 

I'm not sure why be_directory wouldn't work for you. What version of rspec are you using? You can also use rspec's predicate_matchers method, when a predicate exists, but it doesn't read nicely as be_predicate.

Here's what I tried:

describe File, "looking for a directory" do

  it "should be directory" do
    File.should be_directory("foo")
  end

  predicate_matchers[:find_the_directory_named] = :directory?
  it "should find directory" do
    File.should find_the_directory_named("foo")
  end

end

And that gave me the following output (run with spec -fs spec.rb):

File looking for a directory
- should be directory
- should find directory

Finished in 0.004895 seconds

2 examples, 0 failures
nicholas a. evans