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.
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.