测试ActiveRecord :: RecordNotFound

时间:2014-07-10 09:56:33

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

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

以下是数据库查询:

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,我可以拯救它并在我的控制器中渲染一个合适的模板。

这是预期的行为,所以我想在我的规格中对它进行测试。我写道:

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

当我运行rspec时:

1) VerseSelector verses missing in database raises an exception Failure/Error: expect(VerseSelector.select_intro_verse).to raise_exception ActiveRecord::RecordNotFound: ActiveRecord::RecordNotFound

对我来说,即使异常被提出,测试也会失败!我怎样才能通过考试?

1 个答案:

答案 0 :(得分:28)

查看rspec-expectations#expecting-errors的文档:

expect(VerseSelector.select_intro_verse).to raise_exception

异常的except语法必须为lambdaproc

expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound)
相关问题