Optimizing Query Specs

tags: [jason] [refactoring] [specs]

TLDR;

Tests were taking a while but I cut them down from half a minute to 1/3 of the time

Before:

Finished in 25.59 seconds (files took 4.84 seconds to load)

After

Finished in 4.61 seconds (files took 4.82 seconds to load)

Post mortem

Things to check into

Should I clean out the database with a after(:all) block?


Slower example code

RSpec.describe User do
  ...

  let!(:found_buyer) do
    found_buyer = FactoryGirl.create(:user)
    FactoryGirl.create(:order, user: found_buyer, state: 'submitted', submitted_at: a_year_ago - 1.day)
    FactoryGirl.create(:order, user: found_buyer, state: 'submitted', submitted_at: now - 1.day)
    found_buyer
  end

  ...

  describe ".recently_found_ids" do
    before do
      @result = User.recently_found_ids
    end

    it 'returns found buyer' do
      expect(@result).to include found_buyer.id
    end

    ...
  end
end

Faster example

RSpec.describe User do
  attr_reader :found_buyer, :repeat_buyer, :lost_buyer, :new_buyer

  before(:all) do
    now = Time.current.beginning_of_hour
    a_year_ago = now - 12.months

    @found_buyer = FactoryGirl.create(:user, email: 'found@gmail.com')
    FactoryGirl.create(:order, user: @found_buyer, state: 'submitted', submitted_at: a_year_ago - 1.day)
    FactoryGirl.create(:order, user: @found_buyer, state: 'submitted', submitted_at: now - 1.day)

    ...

  end

  describe ".recently_found_ids" do
    let(:recently_found_result) { User.recently_found_ids }

    it 'returns found buyer' do
      expect(recently_found_result).to include found_buyer.id
    end

    ...
  end
end