【问题标题】:Test for ActiveRecord::RecordNotFound测试 ActiveRecord::RecordNotFound
【发布时间】:2014-08-31 15:37:01
【问题描述】:

当模型无法检索记录时,我的应用程序正在向控制器传播 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

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

【问题讨论】:

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


    【解决方案1】:

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

    expect(VerseSelector.select_intro_verse).to raise_exception
    

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

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

    【讨论】:

    • 必须是 lambda 或 proc - 应该加粗:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多