Including shared examples in RSpec

We’ve been using RSpec in testing of Enectiva since the beginning because of hwo expressive it is and how it helps us to structure test cases.

One of the features which makes the later possible are shared contexts and shared examples. We use them quite often and, admittedly, there’re test files which take it to the extreme. However, there are valid use cases for both shared context and shared examples and it’s worth understanding them.

By default, we use include_examples for inclusion of an example group into a context. It works fine: it blocks from the shared group get injected into the current context along with any calls to let or before. In rare cases, though, this might cause a problem by mixing the current context with the context of the example group (especially rewriting values defined by let).

In such cases, we used to wrap the call to include_examples into a special context (or alternatively wrapped the shared example group in a context) which either had to be anonymous or it stuttered:

context do
    include_examples 'returns 400 with an error'
end

# or

context 'returns 400 with an error' do
    include_examples 'returns 400 with an error'
end

Recently, by wandering over the docs because of an unrelated issue, we discovered, that RSpec has s feature for this: it’s a method called it_behaves_like.

It is identical to include_examples with a small semantic difference: it wraps the example group in its own context — exactly what we do with less typing and stuttering! The only disadvantage is a different naming scheme of the example group.

Surprisingly, RSpec has had this feature at least since 2.6 and we just didn’t know about it; so, once again, it’s worth reading the docs thoroughly.

We're looking for developers to help us save energy

If you're interested in what we do and you would like to help us save energy, drop us a line at jobs@enectiva.cz.

comments powered by Disqus