当模型无法检索记录时,我的应用程序正在将 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 的语法必须是lambda
或proc
:
expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound)
关于ruby-on-rails - 测试 ActiveRecord::RecordNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673532/