bogdanrada
2/6/2014 - 7:28 AM

Set session for integration tests Rails

Set session for integration tests Rails

class RackSessionTestMiddleware   


  class << self     
      
    def session_data
      @@session_data||={}
    end
    
    def session_data=(value)
      @@session_data = value 
    end
    
  end
    
  def initialize(app, session_keys)
    @app = app
    @session_keys = session_keys
  end
 
  def call(env)
   

      rack_session =   ::Rack::Request.new(env).session
      
      if self.class.session_data.present? && self.class.session_data.is_a?(Hash) && self.class.session_data[:bypass].blank? 
      
        self.class.session_data.each { |k, v|  rack_session[k] = v }

      elsif self.class.session_data.present? && self.class.session_data.is_a?(Hash) && self.class.session_data[:bypass].present?

        # do nothing with the session ( this in for cases when you really need to do the whole login process) 

      else
        @session_keys.each{|key|   rack_session.delete(key.to_s)  } #avoiding clearing the flash
      end
    
        
    @app.call(env)
  end
 
  
end



 
Rails.configuration.middleware.use RackSessionTestMiddleware, ["user"] if Rails.env.test?