我在编写一些小型ruby程序时正在学习TDD。我有以下课程:
class MyDirectory
def check(dir_name)
unless File.directory?(dir_name) then
raise RuntimeError, "#{dir_name} is not a directory"
end
end
end
我试图用这个rspec测试来测试它。
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
它永远不会工作,我不明白rspec输出有什么问题。
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)>'
我希望这是一件我很想念的简单事,但我只是没有看到它。
答案 0 :(得分:41)
如果要检查异常,则必须将其与lambda的测试区分开来,否则异常会冒泡。
lambda {one.check("donee")}.should raise_error(RuntimeError, "donee is not a directory")
编辑:由于人们仍然使用这个答案,这里是在Rspec 3中做什么:
expect{one.check("donee")}.to raise_error(RuntimeError, "donee is not a directory")
不再需要lambda,因为expect语法采用可选块。
答案 1 :(得分:1)
现在应该被弃用,而不是这个
-> { described_class.new('InValidParam') }
.should raise_error(RuntimeError)
# or
lambda { described_class.new('InValidParam') }
.should raise_error(RuntimeError)
使用这个:
expect { described_class.new('InValidParam') }.to raise_error(RuntimeError)
https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher