Ruby on rails 如何处理Rspec中的Mongoid::Errors::DocumentNotFound?

Ruby on rails 如何处理Rspec中的Mongoid::Errors::DocumentNotFound?,ruby-on-rails,mongodb,rspec,mongoid,Ruby On Rails,Mongodb,Rspec,Mongoid,我有一个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_

我有一个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

在这里,您没有创建对象@另一个用户文章。首先为另一个用户文章模型加载fixture,然后在场景的前一部分中创建此对象。

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

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

或者你可以决定你的控制器在这种情况下应该做的是在控制器级别显式地呈现一个404:rescue异常(无论是在操作中还是通过
rescue\u from
),在这种情况下,你的规范应该按原样通过。

expect{…}。引发\u错误
部分正是我所缺少的。非常感谢你!我应该补充一点,在我发现使用
expect(something)
不起作用之前,我一直在为此伤脑筋。它必须在一个进程中。对象已经创建,但我正试图用另一个用户加载它。正如我在问题中明确指出的,我的问题是如何处理测试中的错误。