Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec not working, or raise not raising?

Tags:

tdd

ruby

rspec

I'm working on learning TDD while writing some small ruby programs. I have the following class:

class MyDirectory
  def check(dir_name)
    unless File.directory?(dir_name) then
      raise RuntimeError, "#{dir_name} is not a directory"
    end
  end
end

and I'm trying to test it with this rspec test.

describe MyDirectory do
  it "should error if doesn't exist" do
    one = MyDirectory.new
    one.check("donee").should raise_exception(RuntimeError, "donee is not a directory")
  end
end

It never works, and I don't understand what is wrong from the rspec output.

Failures:

  1) MyDirectory should error if doesn't exist
     Failure/Error: one.check("donee").should raise_error(RuntimeError, "donee is not a directory")
     RuntimeError:
       donee is not a directory
     # ./lib/directory.rb:4:in `check'
     # ./spec/directory_spec.rb:9:in `block (2 levels) in <top (required)>'

I'm hoping this is something simple that I'm missing, but I'm just not seeing it.

like image 732
gdziengel Avatar asked Feb 09 '11 15:02

gdziengel


1 Answers

If you are checking for an exception, you have to separate that from your test with lambda or the exception will bubble up.

 lambda {one.check("donee")}.should raise_error(RuntimeError, "donee is not a directory")

Edit: Since people still use this answer, here is what to do in Rspec 3:

 expect{one.check("donee")}.to raise_error(RuntimeError, "donee is not a directory")

The lambda is no longer necessary because the expect syntax takes an optional block.

like image 156
Michael Papile Avatar answered Sep 16 '22 22:09

Michael Papile