Using build_stubbed Instead of create in FactoryGirl
In this guide we will refactor our application to use the more efficient build_stubbed FactoryGirl method instead of the create method.
Guide Tasks
  • Read Tutorial

In the last lesson we walked through how to integrate FactoryGirl factories into our application, which cleaned up the test code, however it's usually a bad idea to use the create method in tests since it can lead to a slow test suite. So in this guide we'll incorporate the build_stubbed method for a quick refactor.

Josh Clayton, from Thoughtbot had this to say on why this type of refactor is usually a good idea:

build_stubbed is the younger, more hip sibling to build; it instantiates and assigns attributes just like build, but that’s where the similarities end. It makes objects look look like they’ve been persisted, creates associations with the build_stubbed strategy (whereas build still uses create), and stubs out a handful of methods that interact with the database and raises if you call them. This leads to much faster tests and reduces your test dependency on a database.

So what do we need to do in order to get this working? Opening up our model spec all we need to do is swap out the method call like below:

# spec/models/notification_spec.rb

    it 'can be created' do
      notification = FactoryGirl.build_stubbed(:notification)
      expect(notification).to be_valid
    end

If you run rspec now you'll see that the tests are still passing and it's sliced over a second from the before. This may not seem like a big deal, however imagine when we have hundreds of tests in the application, I promise that you'll appreciate the improvement!

Using the create method

large

Using the build_stubbed method

large

With that working now we can build out more functionality with more efficient tests.

Resources