Search code examples
ruby-on-railsrubyrspecrspec-rails

How to Test The Current User using RSPEC & Here is my controller


This is the AdminController Which is checking the current account and current Role of the user using session in the first action and in the second action we are checking the current role of current user as there are multiple roles for each user.

class AdminController < ActionController::Base
  protect_from_forgery
  skip_before_action :verify_authenticity_token

  def current_account
    if session[:current_account_id].present?
      Account.find(session[:current_account_id])
    end
  end

  def current_role
    if current_account.present?
      current_account.account_users.find_by(user: current_user).admin_role
    else
      AccountUsers::DEFAULT_USER_ROLE
    end
  end
end 

Solution

  • You can create an ordinary user with FactoryBotRails

    let(:user) { create :user }
    

    and stub current user like this for example

    allow_any_instance_of(AdminController).to receive(:current_user).and_return(user)