ruby on rails - How to write rspec tests for controllers that assume authentication -


for controllers assume user authenticated, how should go writing tests?

i don't need keep testing login feature, best inject user or whatever authentication assumes somehow?

my application_controller includes module "current_user".

module currentuser   def self.included(base)     base.send :helper_method, :current_user   end    def current_user     ... # returns user model instance   end end  class applicationcontroller < actioncontroller::base   include currentuser 

then have admin controller has before_action method makes sure current_user present.

you can achieve writing concern, , include every spec controller, in concern support utility methods login system.

so code like:

spec/support/controller_authentication_helper.rb

module controllerauthenticationhelper extend activesupport::concern   module classmethods     def login_user       before         # expect using devise here, if not, modify below line         request.env['devise.mapping'] = devise.mappings[:user]         @current_user = factorygirl.create(:user, :confirmed, :verified)         sign_in @current_user       end     end   end end  rspec.configure |config|   config.include controllerauthenticationhelper, type: :controller end 

so test easy like:

require 'rails_helper'  describe mycontroller, type: :controller   # use method login   login_user   # can access current_user anywhere in test end 

now becomes simple! idea comes source code of devise


Comments