How to Speed Up Your Tests via :build_stubbed

Rspec is an awesome thing that was created for ruby community. Most of us write tests. However, sometimes in large projects our test becomes very slow. So, each launch of the test really hurts and it does not meter whether you launch your test before commit/push or on CI. When it takes over 30 minutes to pass your test suit, something definitely went wrong.

There are many things that you can improve: database clearing, perform caching, stub external requests and so on.

In our project, we use FactoryGirl (FactoryBot). Here I will try to describe how :build_stubbed can help us to improve the test speed.

create:

FactoryBot.create(:comment)

In this case we will create comment object and all association for it.

build:

FactoryBot.build(:comment)

Warning: Here is a misconception, we did not save object but we still will have requests to our database if factory has an associations!

:build does not create object - but it creates all association to that object.