ruby-on-rails - 测试 ActiveRecord::RecordNotFound

标签 ruby-on-rails ruby activerecord ruby-on-rails-4 rspec

当模型无法检索记录时,我的应用程序正在将 ActiveRecord::RecordNotFound 传播到 Controller 。

这是数据库查询:

def self.select_intro_verse
  offset = rand(IntroVerse.count)
  IntroVerse.select('line_one', 'line_two', 'line_three', 'line_four', 'line_five').offset(offset).first!.as_json
end

first! 如果没有找到记录,则引发一个 ActiveRecord::RecordNotFound,我可以挽救它并在我的 Controller 中呈现一个合适的模板。

这是预期的行为,因此我想在我的规范中对其进行测试。我写道:

context "verses missing in database" do
  it "raises an exception" do
    expect(VerseSelector.select_intro_verse).to raise_exception
  end
end

当我运行 rspec 时:

1) 数据库中缺少 VerseSelector 经文引发异常 失败/错误:expect(VerseSelector.select_intro_verse).to raise_exception ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound

对我来说,即使引发异常,测试也会失败!我怎样才能通过测试?

最佳答案

在文档中查找 rspec-expectations#expecting-errors这个:

expect(VerseSelector.select_intro_verse).to raise_exception

应该是except exception 的语法必须是lambdaproc:

expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound)

关于ruby-on-rails - 测试 ActiveRecord::RecordNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673532/

相关文章:

ruby-on-rails - 从 3.2.12 到 4.2.0 的 Rails 查询转换不返回任何内容

ruby-on-rails - ruby/rails 根据字符串数组对记录数组进行排序

ruby - 根据索引在Ruby中将数组拆分为多个数组

ruby-on-rails - Rails 迁移管理 - 最佳实践?

ruby-on-rails - 在 Rails 3 中禁用 BLOB 日志记录

ruby-on-rails - 我无法让 git 忽略我的 Ruby on Rails 项目的 tmp 文件夹

ruby-on-rails - 如何按年/月和总和值对 ruby​​ 文字散列进行分组

ruby - 创建/编辑 Vagrant base box 以预安装 Recipe

mysql - 如何在 codeigniter 中使用 where 和 join

mysql - 从 Rails 中的事件记录中获取特定列值