简体   繁体   中英

How to handle Mongoid::Errors::DocumentNotFound in Rspec?

I have an ArticleController with the following code :

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

And the following test:

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

However, when I start the test, I get the following error (which is normal), but I wonder how to handle that so my test can pass?

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

I thought about changing my controller method by this one, but that does not seems right to me :

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

You can either decide that the right thing for your code to do in this circumstance is to raise an exception, so change your spec to

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

or you can decide that what your controller should do in this case is explicitly render a 404: rescue the exception at the controller level (either in the action or via rescue_from ), in which case your spec should pass as is.

Here you didnt created the object @another_user_article. First load fixtures for another_user_article model, then create this object in before part of scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM