Skip to content

Instantly share code, notes, and snippets.

@alexford
Created November 10, 2018 14:27
Show Gist options
  • Save alexford/8718d2930db14ab50bdf1f799e4b66af to your computer and use it in GitHub Desktop.
Save alexford/8718d2930db14ab50bdf1f799e4b66af to your computer and use it in GitHub Desktop.
Mocking a specific instance of an ActiveRecord model that hasn't yet been queried
require 'rails_helper'
RSpec.describe 'Mocking specific instance' do
let!(:student_to_stub) { create_list(:student, 3).first }
let(:stubbed_name) { junk }
before do
stub_model(Student, :first_name, { id: student_to_stub.id }, stubbed_name)
end
subject { Student.find(student_to_stub.id) }
it 'stubs matching instances' do
expect(subject.first_name).to eq stubbed_name
expect(Student.last.first_name).not_to eq stubbed_name
end
def stub_model(klass, method, conditions = {}, return_value = nil)
allow_any_instance_of(klass).to receive(method).and_wrap_original do |method, *args|
if conditions.none? || conditions.all? { |k,v| method.receiver.send(k) == v }
block_given? ? yield(method.receiver, *args) : return_value
else
method.call(*args)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment