How do I get the exception Mongoid :: Errors :: DocumentNotFound released on Mongoid

4

To try to do a test similar to this below capture the exception of a nonexistent 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 do not know if there is anything related to 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 am I doing wrong?

    
asked by anonymous 21.09.2016 / 19:34

1 answer

2

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

You need to use a block . In 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 expect method).

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

(Note the parenthesis change, for the key)

Note that in this case, the expect method will capture the exception thrown by your code and then check if it is the one defined in your test.

    
24.10.2016 / 14:09