简体   繁体   中英

How to test my ApplicationController, when a method has to be setup?

I am using rspec and having issues trying to test my ApplicationController.

Is it possible to somehow set the values inside the controllers? This is what I have now:

class ApplicationController < ActionController::Base
  include CurrentUser
  before_action :load_account


  private
   def load_user
      @account = current_user.account if current_user.present?
   end
end

The included module just adds a current_user method that returns a User.

module CurrentUser
  def self.included(base)
    base.send :helper_method, :current_user
  end

  def current_user
    User.find_by(.....)  # returns a User object
  end
end

So when I am testing my controllers, I don't need to test the functionality of current_user.rb , can I somehow inject the value of current_user before my tests run?

example controller spec:

require 'rails_helper'

RSpec.describe ProductsController, type: :controller do
  it "...." do
    get :new
    expect(response.body).to eq("hello")
  end
end

But currently any controller that expects a current_user is failing because it is nil.

You could setup a custom before :each in the config which stubs the current_user so it doesn't break your tests

RSpec.configure do |config|
  config.before(:each, current_user_present: true) do
    account = double(:account)
    current_user = double(:current_user, account: account)
    expect(controller).to receive(:current_user).and_return(current_user)
    expect(current_user).to receive(:present?).and_return(true)
    expect(current_user).to receive(:account).and_return(account)
  end
end

RSpec.describe ProductsController, type: :controller, current_user_present: true do
  it "..." do
    #...
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM