How do I get Exception Mongoid::Errors::Documentnotfound released on Mongoid

Asked

Viewed 121 times

4

I’m trying to do a test similar to the one below to capture the Exception of a non-existent document

expect(Produto.find('57e2bf76ce222fd11258cd4e')).to raise_error(Mongoid::Errors::DocumentNotFound)

the Exception message being passed is shown, however the test does not pass :(

Mongoid::Errors::DocumentNotFound:
message:
  Document(s) not found for class Produto with id(s) 57e2bf76ce222fd11258cd4e.
summary:
  When calling Produto.find with an id or array of ids, each parameter must match a document in the database or this error will be raised. The search was for the id(s): 57e2bf76ce222fd11258cd4e ... (1 total) and the following ids were not found: 57e2bf76ce222fd11258cd4e.
resolution:
  Search for an id that is in the database or set the Mongoid.raise_not_found_error configuration option to false, which will cause a nil to be returned instead of raising this error when searching for a single id, or only the matched documents when searching for multiples.
from ~/.rvm/gems/ruby-2.3.1@api/bundler/gems/mongoid-71c29a805990/lib/mongoid/criteria.rb:457:in `check_for_missing_documents!'

I don’t know if it has anything to do with the last line of the message

mongoid/criteria.rb:457:in `check_for_missing_documents!'

but what I notice is that raise_error is not working in this situation. What I am doing wrong?

1 answer

2

The problem is that your code is running (and throwing an exception) and passed as parameter to the method expect, without giving Rspec the chance to perform any kind of verification.

You need to use a block. This way, the execution of the contents of the block will not be done immediately, but determined by the method you are calling (in this case the method expect).

expect { Produto.find('57e2bf76ce222fd11258cd4e') }.to raise_error(Mongoid::Errors::DocumentNotFound)

(Note the parenthesis change by the key)

Notice, in this case, the method expect will capture the exception thrown by your code and then check if it is the same as defined in your test.

  • really, had already corrected but still thank you very much for the explanation ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.