NoMethodError:未定义的方法`RuntimeError'

Tar*_*ast 3 ruby error-handling ruby-on-rails

我在Ruby库中编写了一些代码(偶然在Rails中使用),它引发了一个RuntimeError,如下所示:

class MyClass
  def initialize(opts = {})
     # do stuff
     thing = opts[:thing]
     raise RuntimeError "must have a thing!" unless thing.present? && thing.is_a?(Thing)
     # more stuff
  end
end
Run Code Online (Sandbox Code Playgroud)

当我在上面运行我新的rspec规范时,看起来有点像:

it "should raise an error if we don't pass a thing" do
  lambda {
    my_class = MyClass.new(:thing => nil)
  }.should raise_exception(RuntimeError)
end
Run Code Online (Sandbox Code Playgroud)

我一直在变得奇怪:

expected RuntimeError, got 
#<NoMethodError: undefined method `RuntimeError' for #<MyClass:0xb5acbf9c>>
Run Code Online (Sandbox Code Playgroud)

Tar*_*ast 11

你可能已经发现了这个问题......啊,单个字符的bug,doncha love em?

这里是.

错误:

 raise RuntimeError "must have a thing!" unless thing.present? && thing.is_a?(Thing)
Run Code Online (Sandbox Code Playgroud)

对:

 raise RuntimeError, "must have a thing!" unless thing.present? && thing.is_a?(Thing)
Run Code Online (Sandbox Code Playgroud)

当然,您也可以继续完全省略RuntimeError:

 raise "must have a thing!" unless thing.present? && thing.is_a?(Thing)
Run Code Online (Sandbox Code Playgroud)

因为它是默认的......


Joh*_*ler 5

你错过了一个逗号:

raise RuntimeError, "must have a thing!" unless thing.present? && thing.is_a?(Thing)
                  ^
Run Code Online (Sandbox Code Playgroud)