1

I have the following controller action:

def index
    @companies = Company.order(:name).includes(:team_members, :user)

    if params[:search].present?
      @companies = @companies.where('name ilike ?', "%#{params['search']}%")
    end
end

and respective rspec test:

before :each do
  allow(Company).to receive(:where)

  get :index, search: 'search_query'
end

it 'filters the companies by the search parameter' do
  expect(Company).to have_received(:where).with('name ilike "%search_query%"')
end

However rspec is not detecting that the "where" method is being called on the Company class. I am getting the following error:

1) CompaniesController GET #index when search parameter is given filters the companies by the search parameter
     Failure/Error: expect(Company).to have_received(:where).with('name ilike "%search_query%"')
       (Company(id: integer, name: string, description: text, season: string, iac_rating: float, funding_history: text, smart_scores: float, created_at: datetime, updated_at: datetime, logo: string, website: string, summary: text, pitch_deck: string, executive_summary: string, unique_factor: text, revenue_burn_rate: text, growth: text, category: string, typical_check_size: string, raising_amount: string, committed_amount: string, hq_location: string, sector: string, num_full_time_founders: string, user_id: integer, display_order: integer) (class)).where("name ilike \"%search_query%\"")
           expected: 1 time with arguments: ("name ilike \"%search_query%\"")
           received: 0 times

What is the proper way to test this? Thanks!

1 Answer 1

0

It's @companies and not Company what's receiving :where.
In your test code you have to show how the mocks descend from Company in the same way @companies descend from Company in the real code. This is necessary to have RSpec match @companies with its respective mock, @companies_mock.

  before :each do
    @companies_mock = double('Company')
    @intermediate_mock = double('Company')

    allow(Company).to receive(:order).and_return @intermediate_mock
    allow(@intermediate_mock).to receive(:includes).and_return @companies_mock

    allow(@companies_mock).to receive(:where)

    get :index, search: 'search_query'
  end

  it 'filters the companies by the search parameter' do
    expect(@companies_mock).to have_received(:where).with('name ilike ?', "%search_query%")
  end

Some time has passed since you asked. Hopefully you'll find it useful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.