Ruby Rspec不工作,或raise不升起?

Ruby Rspec不工作,或raise不升起?,ruby,tdd,rspec,Ruby,Tdd,Rspec,我正在学习TDD,同时编写一些小型ruby程序。我有以下课程: 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 err

我正在学习TDD,同时编写一些小型ruby程序。我有以下课程:

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)>'
故障:
1) 如果MyDirectory不存在,则应出错
失败/错误:一。检查(“受赠人”)。应引发_错误(RuntimeError,“受赠人不是目录”)
运行时错误:
donee不是目录
#./lib/directory.rb:4:in'check'
#./spec/directory_spec.rb:9:in'block(2层)in'

我希望这是我遗漏的一些简单的东西,但我只是看不到它。

如果要检查异常,必须将其与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语法需要一个可选块。

我使用了
expect(…).to
而不是
expect{…}.to
,这个答案最终帮助我找到了错误!请记住,如果使用括号而不是块,则可能会出现异常。请参阅块语法应用于预期的异常。这太痛苦了。回答得好!我从来没有想到过这一点