[英]Test for ActiveRecord::RecordNotFound
当模型无法检索记录时,我的应用程序正在将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
对我来说,即使异常被提出,测试也会失败! 我怎样才能通过考试?
查看文档中的rspec-expectations#expecting-errors
:
expect(VerseSelector.select_intro_verse).to raise_exception
应该是except
异常的语法必须是lambda
或proc
:
expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.