我在 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 - NoMethodError : undefined method `RuntimeError' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5757145/