ruby on rails - RSpec 3 - raising an error on purpose to test it is rescued -


consider simple method -

def my_method(users)   eligible_users = []    users.each |u|     # go next user unless eligible     next unless is_eligible?(u)      begin       update_user(u)       eligible_users << u     rescue       puts "error occured"       # prints other stuff error       next     end   end end 

a key feature of method loops through users continues next user if given user throws error.

if writing spec tests this, i'd love pass array of 3 users , purposely have error out on first user. can check 2nd , 3rd still correctly processed.

how go raising error on purpose one of result sets?

i thinking stub is_eligible? , return error 1 of result , true remainder -

allow_any_instance_of(myclass).to receive(:is_eligible?).and_return(   raise standarderror.new,   true,   true ) 

as expected, doesn't work. other approaches?

thanks!

i can't answer question, rather doing begin resuce thing,you can follow approach,

  • make update_user return true or false.
  • keep array of users falied update.
  • return object

response: { status: "failure", message: "falied update #{pluralize(failed_users_array.count, 'user')}", failures: failed_users_array.join(", ") } failures and

response: { status: "success", message: "#{pluralize(users.count, 'user')} updated successfully" } success.

now can test,

  • have 2 cases, 1 can test failures , when can test success.

just stub response object.

for raising errors, have .and_raise("some tezt or standarderror.new") , thats in docs.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -