Testing Error Handling - Rails on Maui

You can simulate error conditions by manually placing =raise “any error message”= statements in your code, and then testing, say in the UI manually. This is a good first step to verify that your error handling is working correctly. You might raise a specific error, if say your payment processor throws a specific type of error.

For the above example, the different methods referenced, such as process_order can get modified with a single line at the beginning, which would be:

1 2 3 4 def process_order raise "Any error message" # Lots of other code that can be commented out end

Then go into the UI and test placing an order. Consider the following questions:

  1. Was the right error message displayed to the user?
  2. Was the right information logged at the correct log level?
  3. Was an automatic email sent regarding the error?

See my prior article Saner Rails Logging for the answers to #2 and #3.

By applying this technique to each of the components of completing a purchase, one can flush out (and handle) nearly all of the different possible errors that could affect a purchase. Give this technique a try in some critical section of the code. You’ll be surprised how well it works. Before giving you the fix to the above code, let’s see if we can write unit and feature tests on our error handling.

This is a companion discussion topic for the original entry at http://www.railsonmaui.com//blog/2013/05/11/testing-error-handling/

That was a useful blog post, thanks!

I should mention that RSpec now uses a new syntax for stubbing and expectations.

For example

PaymentGateway.stub(:charge) { raise ... }
# becomes
allow(PaymentGateway).to receive(:charge) { raise ... }


email.to.should_not include(order.user.email)
# becomes
expect(email).to_not include(order.user.email)