Search code examples
ruby-on-railsrubyruby-on-rails-4rspecrspec-rails

Test if method hits the database


I have the following method and I want to make sure that it won't hit the database unless the subdomain changes.

class ApplicationController < ActionController::API
  def current_account
    unless @current_account && @current_account.subdomain == request.subdomain
      @current_account = Account.find_by subdomain: request.subdomain
    end
    @current_account
  end
end

How can I test the lest one?

require 'rails_helper'
RSpec.describe ApplicationController, type: :controller do
  controller do
    def index
    end
  end

  describe 'current_account' do
    before(:each) do
      FactoryGirl.create(:account, subdomain: 'subdomain1')
      FactoryGirl.create(:account, subdomain: 'subdomain2')
      request.host = 'subdomain1.example.com'
    end

    it 'sets the current_account based on the subdomain' do
      get :index
      expect(subject.send(:current_account).subdomain).to eq('subdomain1')
    end

    it 'changes the current_account when subdomain changes' do
      get :index
      request.host = 'subdomain2.example.com'
      get :index
      expect(subject.send(:current_account).subdomain).to eq('subdomain2')
    end

    xit 'does not hit the database if subdomain does not change' do
      get :index
      # expect to hit the db
      get :index
      # expect to not hit the db
    end
  end
end

I have tried expect(Account).to receive(:find) with no success.


Solution

  • I usually install this gem for that purpose:

    https://github.com/brigade/db-query-matchers - RSpec matchers for database queries

    Example usage:

    it 'does not make database queries' do
      expect { subject.make_no_queries }.to_not make_database_queries
    end