我在 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
当我在上面运行我的新 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
我不断得到一些奇怪的东西:
expected RuntimeError, got
#<NoMethodError: undefined method `RuntimeError' for #<MyClass:0xb5acbf9c>>
最佳答案
您可能已经发现了问题...啊,单字符错误,doncha love em?
在这里。
错误:
raise RuntimeError "must have a thing!" unless thing.present? && thing.is_a?(Thing)
右:
raise RuntimeError, "must have a thing!" unless thing.present? && thing.is_a?(Thing)
当然,您也可以直接忽略 RuntimeError:
raise "must have a thing!" unless thing.present? && thing.is_a?(Thing)
因为无论如何它都是默认的...
关于ruby-on-rails - 无方法错误 : undefined method `RuntimeError' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5757145/