ruby-on-railsrubyrspecmockingruby-grape

Rspec mock ActiveRecord::Relation instead of class object


I want to mock one line from my endpoint:

InquiryProcessFilters::CompanyName.new(params[:filters][:company_name].downcase).call

So I've mock:

let(:company_name_filter_mock) { instance_double(InquiryProcessFilters::CompanyName) }

before do
  allow(InquiryProcessFilters::CompanyName).to(receive(:new).and_return(company_name_filter_mock))
  allow(company_name_filter_mock).to receive(:call).and_return(second_inquiry_process)
end

The problem is that my class from endpoint returns result as ActiveRecord_Relation and this is my desired result. How to update my mock to achieve that?


Solution

  • I can see two options.

    If you care about not touching DB in the spec and it's enough to get Enumerable, assign an array to second_inquiry_process, e.g.:

    let(:second_inquiry_process) { [inquiry_process_instance] }
    

    or with FactoryBot

    let(:second_inquiry_process) { build_list :inquiry_process, 1 }
    

    If you want to have full AR relation (and I suppose you do), create records in the db and assign them to the variable, e.g.:

    let(:inquiry_process_instance) { create :inquiry_proces }
    let(:second_inquiry_process) { InquiryProcess.where(id: inquiry_process_instance.id) }