Ruby on Rails testing

Ruby on Rails / Testing – simple stubs with RSpec

Ruby on Rails / Testing – simple stubs with RSpec January 12, 20184 Comments

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.

If you want to stub any instance of a given object you can use this code:

allow_any_instance_of(Post).to receive(:title).and_return('title')

Using this code forces any instance of Post model to return title when calling #title method

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

4 comments

  1. You really make it seem so easy with your presentation but I find this topic tto be actually something
    that I think I wpuld never understand. It seems too complex
    and extremely broad for me. I’m loking forward for your next post, I’ll try to get the hang of it!

Leave a Reply

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