If you are not sure if you should write tests for your application check my article about it.

Mostly, writing a spec you would like to stub classes used in a class that you are testing. We don’t want to hit the database if it’s not needed. In order to do this, you have to use stubs. Stubs are instructions that allow to call given method and return desired value without calling code inside the method.

There are three base steps to do this:

1. Allow given class or class instance
2. To receive given method
3. And return desired results

If you have Post model and #title method you can use following code to stub model instance:

allow(post).to receive(:title).and_return('title')

If your method takes one or more arguments there is one extra step: with part.

allow(post).to receive(:title).with(argument_1, argument_2).and_return('title')

The goal is to control how exactly we call given method.

Having problems with tests for your Ruby on Rails application?

Hit me on twitter or use contact form and let me know how can I help you!

One Comment

  1. You should also discuss allow any instance.

Leave a Comment

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