Read more

How to disable cookies in cucumber tests

Arne Hartherz
March 20, 2013Software engineer at makandra GmbH

Unfortunately, Capybara does not offer a switch to disable cookies in your test browser. However, you can work around that by using a tiny Rack middleware -- it works for both Selenium and non-Selenium tests.


Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Wouldn't it be nice to say something like this?

Given cookies are disabled
When I try to sign in
Then I should see "Can't sign you in. Please enable cookies."

You can! Put the code below into some place like lib/rack/cookie_stripper.rb.

module Rack
  class CookieStripper
    
    ENABLED = false

    def initialize(app)
      @app = app
    end

    def call(env)
      Request.new(env).cookies.clear if ENABLED
      @app.call(env)
    end

  end
end

Next, configure your application to use that middleware by putting this inside your Rails initializer block (config/environment.rb for Rails 2, config/application.rb for Rails 3):

require 'lib/rack/cookie_stripper.rb'
config.middleware.use Rack::CookieStripper

The middleware will simply strip all cookies from the request, so they'll never reach the application. It is disabled by default, and we'll switch it on only for certain tests.

Enable it in your scenario by using a step like this:

Given /^cookies are disabled$/ do
  overwrite_constant :ENABLED, false, Rack::CookieStripper
end

The overwrite_constant step is from Uli's excellent card on how to overwrite and reset constants within Cucumber features. By using it, the constant will automatically be reset so your scenario doesn't affect other tests.

Posted by Arne Hartherz to makandra dev (2013-03-20 19:44)