【问题标题】:How to handle Mongoid::Errors::DocumentNotFound in Rspec?如何处理 Rspec 中的 Mongoid::Errors::DocumentNotFound?
【发布时间】:2012-04-30 11:11:10
【问题描述】:

我有一个带有以下代码的 ArticleController:

def edit
  @article = current_user.articles.find(params[:id])
end

还有以下测试:

describe "GET 'edit'" do
  it "should fail when signed in and editing another user article" do
    sign_in @user
    get :edit, :id => @another_user_article.id
    response.should_not be_success
  end
end

但是,当我开始测试时,我收到以下错误(这是正常的),但我想知道如何处理以便我的测试可以通过?

Failure/Error: get :edit, :id => @another_user_article.id
Mongoid::Errors::DocumentNotFound:
   Document not found for class Article with id(s) 4f9e71be4adfdcc02300001d.

我想过用这个来改变我的控制器方法,但这对我来说似乎不合适:

def edit
  @article = Article.first(conditions: { _id: params[:id], user_id: current_user.id })
end

【问题讨论】:

    标签: ruby-on-rails mongodb rspec mongoid


    【解决方案1】:

    您可以决定在这种情况下您的代码要做的正确事情是引发异常,因此将您的规范更改为

    expect { get :edit, :id => @another_user_article.id}.to raise_error(Mongoid::Errors::DocumentNotFound)
    

    或者你可以决定你的控制器在这种情况下应该做的是显式地渲染一个 404:在控制器级别救援异常(在操作中或通过rescue_from),在这种情况下你的规范应该按原样通过.

    【讨论】:

    • expect { ... }.to raise_errorpart 正是我所缺乏的。非常感谢!
    • 我应该补充一点,我正在为此努力,直到我发现使用 expect(something) 不起作用。它必须在一个过程中。
    【解决方案2】:

    这里你没有创建对象@another_user_article。首先为 another_user_article 模型加载夹具,然后在部分场景之前创建此对象。

    【讨论】:

    • 对象已经创建,但我正在尝试使用其他用户加载它。正如我在问题中明确指出的那样,我的问题是如何在测试中处理该错误。
    猜你喜欢
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多