2

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
Dominic Goulet
  • 7,983
  • 7
  • 28
  • 56

2 Answers2

5

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.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174
0

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.

Mohanraj
  • 4,056
  • 2
  • 22
  • 24
  • The object is already created, but I'm trying to load it with a different user. As I clearly stated in the question, my problem is how to handle that error in the tests. – Dominic Goulet Apr 30 '12 at 11:53