Controller

stub controller's instance variable which is set in before action

class ContactsController < ApplicationController 
  before_action :find_user
  def index
    @contacts = @user.contacts
  end

  private

  def find_user
    @user = User.first
  end
end

# testing for the controller

require 'rails_helper'
RSpec.describe ContactsController, type: :controller do
  describe 'GET #index' do
    let!(:user1) { User.create(name: 'user1') }
    let(:user2) { User.create(name: 'user2') }
    let(:contact) { Contact.create(numbers: '12345678') }
    before do
      user2.contacts << contact
      user2.save!
    end
    it do
      # described_class.any_instance.stub(:find_user) # (old syntax) stub out the original find_user method call
      allow_any_instance_of(described_class).to receive(:find_user).and_return(user) # new syntax
      controller.instance_variable_set(:@user, user2) # set @user instance variable as user2
      get :index
      expect(controller.instance_variable_get(:@contacts).first.id).to eq(contact.id)
    end
  end
end

Reference

results matching ""

    No results matching ""