Four-Phase test with RSpec’s raise_error/raise_exception

Greg Lazarev
Sep 3 · 1 min read

Have you ever written an RSpec test similar to this?

It’s not clearly obvious which part of this test is the “exercise” and which is the “verify” phase, as outlined by xUnit’s Four-Phase Test.

Additionally, if you use HoundCI or RuboCop to lint your Ruby code, you may see a warning like (with default configuration):

Style/BlockDelimiters: Avoid using {…} for multi-line blocks.

You could switch to do...end block style, but doesn't look very idiomatic.

There is an alternative to writing this, where the phases are more distinct and identified more easily. With the help of Ruby lambda we can rewrite our test as:

With this approach, we can clearly identify the “setup”, “exercise”, and “verify” phases. As a bonus, there’s no need to do syntax gymnastics to please our Hound or RuboCop!

Written by

Co-founder of HoundCI

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade