Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara & Cucumber | Getting cookies

I'm trying to get cookie values in the Cucumber step:

Step definitions

When /^I log in$/ do
  # code to log in
end

Then /^cookies should be set$/ do
  cookies[:author].should_not be_nil
end

Controller

class SessionsController < ApplicationController
  def create
    cookies[:author] = 'me'
    redirect_to authors_path
  end
end

But it doesn't work:

Result

expected: not nil
     got: nil

In the RSpec examples, all works just fine:

Controller Spec

require 'spec_helper'

describe SessionsController do
  describe 'create' do
    it 'sets cookies' do
      post :create
      cookies[:author].should_not be_nil
    end
  end
end

How can I get cookie values in Cucumber steps using Capybara?

Thanks.

Debian GNU/Linux 6.0.4;

Ruby 1.9.3;

Ruby on Rails 3.2.1;

Cucumber 1.1.4;

Cucumber-Rails 1.2.1;

Capybara 1.1.2;

Rack-Test 0.6.1.

like image 956
Shamaoke Avatar asked Feb 10 '12 07:02

Shamaoke


2 Answers

Step Definitions

Then /^cookies should be set^/ do
  Capybara
    .current_session # Capybara::Session
    .driver          # Capybara::RackTest::Driver
    .request         # Rack::Request
    .cookies         # { "author" => "me" }
    .[]('author').should_not be_nil
end

This works, however, I'm still looking for a less verbose way. Moreover, I'd like to know how to get the session data in a step definition.

Updated

To get the session data one should do the following:

Step Definitions

Then /^session data should be set$/ do
  cookies = Capybara
    .current_session
    .driver
    .request
    .cookies

  session_key = Rails
    .application
    .config
    .session_options
    .fetch(:key)

  session_data = Marshal.load(Base64.decode64(cookies.fetch(session_key)))

  session_data['author'].should_not be_nil
end

This is quite verbose too.

like image 78
Shamaoke Avatar answered Sep 29 '22 02:09

Shamaoke


It seems that Selenium API has changed. The suggested solution did not work, but I after spending a bit of time looking around, I found a solution.

To save a cookie:

browser = Capybara.current_session.driver.browser.manage
browser.add_cookie :name => key, :value => val

To read a cookie:

browser = Capybara.current_session.driver.browser.manage
browser.cookie_named(key)[:value]

cookie_named returns an array consisting of "name" and "value", so we need an extra reference to extract cookie value.

like image 30
Vasily Avatar answered Sep 29 '22 02:09

Vasily