Stubbing and Mocking with RSpec

By Clemens Helm

Today we have a guest post by Clemens Helm of Codeship.io. This is the ninth Testing Tuesday episode. Every week Codeship shares insights and opinions on the software testing space. Drop by every Tuesday to learn more! Last week they talked about Behavior-Driven Integration and Unit Testing with Cucumber and RSpec.


Specifying examples with RSpec

When you work Outside-In with Behavior-Driven Development your scenarios take care of checking that your application works from a user’s perspective. They don’t care at all how you implement something.

Let’s say we refactor a class of our application. Then we permanently want to make sure that we didn’t break anything by moving things around. Unfortunately this is impossible with integration tests, because they are just too slow.

This is why we write examples that explain how our single components – like for example classes – should behave. These examples should be fast, so we can run them continuously while we make changes to a class. And they should only specify behavior of the own scope and ignore all behavior of other classes.

I am working in a Ruby on Rails App so I use RSpec to write these examples in this screencast, but there are Spec frameworks for a lot of other languages that work similar. Check out the further info section below to find out more.

Stubbing and Mocking with RSpec

Stubbing and Mocking makes your component examples independent of other components. You can stub methods on objects to let them return whatever you like. And you can use mock objects to replace instances of other classes. This screencast shows how to stub and mock using RSpec.

Up next Testing Tuesday: Design your application with RSpec

Stubbing and Mocking also facilitate designing software. They let you specify the code you wish you had without relying on code that’s already there. This makes you build better designed and more readable code. Check back next Testing Tuesday to find out how!

Further info:

About the Author

I’m a passionate web application developer and Ruby on Rails enthusiast. I love building stunning web applications and start-ups that rock. And I love boarding – on the street, on water, on snow – there’s a board for every season. You can follow me on Twitter.


See More Posts About:

Software Development Tools


Posted by Clemens Helm

LinkedIn Website