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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)