How do I set up a session value in Capybara?

Nerian picture Nerian · Dec 17, 2011 · Viewed 17k times · Source

I am developing an app for Shopify and I want to do integration testing.

I need to be able to store some values in the session variable, so that authentication works.

How could I do that?

I use Capybara and Capybara-webkit.

Answer

ronen picture ronen · Feb 24, 2013

The accepted answer suggests rack_session_access. It works by inserting middleware controllers to edit and update the session state, then has capybara visit that page and submit a form with the session data. Very ingenious! But unnecessary if you are using Warden (directly or through Devise).

Warden has a hook on_next_request that gives access to the warden mechanism, which can be used to set session keys directly. I threw this together to bundle it up in rspec:

Create spec/support/inject_session.rb:

module InjectSession
  include Warden::Test::Helpers

  def inject_session(hash)
    Warden.on_next_request do |proxy|
      hash.each do |key, value|
        proxy.raw_session[key] = value
      end
    end
  end
end

In spec/spec_helper.rb include the module in feature specs:

RSpec.configure do |config|
    config.include InjectSession, :type => :feature
end

Then sample use in a spec might be:

   inject_session :magic => 'pixie dust', :color => 'pink' 
   visit shopping_cart_path
   page.should be_all_sparkly_and_pink # or whatever