session snippets

Testing sessions with Sinatra and Rack::Test

Tagged session, test, sinatra, rack, cookie, rack::test, mocha  Languages ruby

You need support for testing sessions when, for example, testing authentication. The only way I've managed to get sessions to work with Sinatra and Rack::Test is by going through the whole stack, in other words calling the authentication controller as shown here:

@user = Factory(:user) # create a dummy user
User.expects(:authenticate).with(any_parameters).returns(@user) # make authenticate return the dummy user
post "/sign-in", {:email => @user.email, :password => @user.password} # login to the application and set a session variable.

After this the session populated and we're logged in when accessing the application again:

post "/articles", {:title => 'Sessions suck', :body => '...'}

On a side note, there are two ways of specifying sessions that used to work, but which no longer work with Sinatra 1.0:

get '/', :env => { :session => {:abc => 'adf'} }
get '/', {}, :session => {:abc => 'adf'}
get '/', {}, "rack.session" => {:abc => 'adf'}

The session is always empty.

There are many discussions about sessions and Rack::Test, but not one of them has a solution that works for me: * rack.session variable is missing env under test environment * Sessions with rspec and Rack.Test

Rails Cells Example

Tagged rails, cells, request, session, params, controller  Languages ruby

This Rails Cells example demonstrates how to: * access the request * access the controller * access the session * access the request parameters * cache data * use dynamic cache keys * access cell parameters * use helpers

class MenuCell < Cell::Rails
  helper :menu
  cache :display, :cache_conf, :expires_in => 1.day

  def display
    @selected = options[:selected]
    @posts ||= Post.paginate(options[:posts])
    render
  end

  protected
    def cache_conf
      # parent_controller.controller_name
      # parent_controller.request or request
      # parent_controller.session
      # parent_controller.params
      { :path => request.fullpath }
    end
end

The cell is rendered by calling:

<%= render_cell :menu, :display, :selected => controller.controller_name %>

See Cells the change log for details.