visit our site

Using Configurable Shared Examples in RSpec

In Development, Testing

by Sergii Boiko by December 21, 2016

Shared examples are a good tool to describe some complex behavior and reuse it across different parts of a spec. Things get more complicated when you have the same behavior, but it has some slight variations for different contexts. In this case it’s easy to end-up having a bunch of separate one-spec behaviors instead of having some way to adjust those peculiarities in a simple way.


To be more specific, let’s create a simple example. We want to describe behavior of different dogs. Every one of them can perform some common actions, but there’re also certain actions they don’t perform at all. For example, Snuff can bark and growl, but doesn’t like to jump. On the other hand, Scooby-Doo likes to jump and flee, but doesn’t growl. Scrappy-Doo is too small to bark, but he likes to growl a lot.

The spec looks great, but we should adjust ‘a normal dog’ behavior for each character, otherwise each context will fail due to unsupported ability.

Using params in shared_examples

Luckily, RSpec supports accepting params for shared_examples, so we can rewrite the spec like this:

Now all specs pass successfully. We use shared_examples params to pass configuration values and adjust the way it matches. Note that this won’t work with usual let-bindings. Shared examples are created and configured at the “compile time”, while let-bindings can be used only at “run time”.

Another nice thing about shared_examples params – is that they are accessible within tests at run-time. So, for very simple specs it’s possible to use them instead of let-bound values. Here is a simple example:

So, instead of using 3 let-bindings for the arguments and the result, we get a very succinct way of writing simple specs.

* Railsware is a premium software development consulting company, focused on delivering great web and mobile applications. Learn more about us.
  • Kaio Cristian Costa Porto de M

    Great Article!

Signup for our weekly newsletter

Want to get more of Railsware blog?

RSS Feed

We're always ready to help!

Contact us