ruby-on-rails - 无方法错误 : undefined method `RuntimeError'

标签 ruby-on-rails ruby error-handling

我在 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/

相关文章:

ruby - 如何使用修改后的 header 制作 HTTP GET?

python-2.7 - 如果列表索引超出范围,则打印

ruby-on-rails - 根据父模型验证模型

javascript - Rails 3 - Javascript :confirm not working for link_to and button_to with :method => :delete

mysql - Rails 迁移文件未将列添加到 Mysql 数据库

android - Android + Google API v2

angular - 将HttpHandler返回的Observable与HttpInterceptor中的另一个合并(Angular 8)

ruby-on-rails - Rails AJAX - 获取下拉选择来填充表格

sql - Rails ActiveRecord 查询以匹配所有参数

ruby-on-rails - 如何使用 ruby​​ 修改 pdf 中的单个页面大小?