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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With