测试ActiveRecord :: RecordNotFound

fko*_*ler 16 ruby activerecord rspec ruby-on-rails ruby-on-rails-4

当模型无法检索记录时,我的应用程序正在将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
Run Code Online (Sandbox Code Playgroud)

first!ActiveRecord::RecordNotFound如果没有找到记录,则引发一个,我可以拯救它并在我的控制器中渲染一个合适的模板.

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

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

当我运行rspec时:

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

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

Зел*_*ный 29

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

expect(VerseSelector.select_intro_verse).to raise_exception
Run Code Online (Sandbox Code Playgroud)

应该是except异常的语法必须是lambdaproc:

expect { VerseSelector.select_intro_verse }.to raise_exception(ActiveRecord::RecordNotFound)
Run Code Online (Sandbox Code Playgroud)