RSpec Ruby Testing: Shared Examples and Shared Context

Basic Rspec testing is extremely intuitive, but it’s very easy for code to get repetitive and start violating the DRY principle. Very often we can find ourselves copy and pasting example after example and subject after subject. Luckily, RSpec gives us the ability to DRY up our code by sharing context and examples in different test example groups.


Let’s look at a very contrived situation in which I am testing the #size ruby method on several different object types, including a custom object I’ve created for my app and want to test.

All the tests pass, which is great, but it’s easy to see where I am repeating myself. DRYing this code up is pretty easy with RSpec’s #shared_examples method. All we have to do is call the method, and in the block we can declare any example we want groups to share. After that, injecting the shared examples is also very intuitive; we just use another RSpec method: #include_examples. Here’s what our re-worked code will look like.

Our code now is much cleaner, and much easier to modify if needed, as we can just change the code inside the #shared_examples block instead of having to go down the list of example groups.


Sharing context works in basically the same way. RSpec features a #shared_context method, where you can define variables, instance variables, methods, etc. inside its block that your upcoming tests should share. We can then inject that context into example groups with the, you guessed it, #include_context method. I couldn’t come up with even a bad example, so here’s some code to showcase shared context that has nothing to do with a real-world situation.

It’s easy to see how useful sharing context between examples can be. Not having to re-define variables and methods for each example makes our code very easy to modify and read. Please also note as long as you inject the context, you can use all those variables and methods across all the different example groups you want. RSpec rules!

Keep coding, keep testing.

Add a Comment

Your email address will not be published. Required fields are marked *