I\'m trying to get cookie values in the Cucumber step:
Step definitions
When /^I log in$/ do
#
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.
Try the show_me_the_cookies
gem.
https://github.com/nruth/show_me_the_cookies
Here is my code of step defenition:
Then /^cookie "([^\"]*)" should be like "([^\"]*)"$/ do |cookie, value|
cookie_value = Capybara.current_session.driver.request.cookies.[](cookie)
if cookie_value.respond_to? :should
cookie_value.should =~ /#{value}/
else
assert cookie_value =~ /#{value}/
end
end
Here is example of output when test fails:
expected: /change/
got: "/edit" (using =~)
Diff:
@@ -1,2 +1,2 @@
-/change/
+"/edit"
(RSpec::Expectations::ExpectationNotMetError)
./features/step_definitions/web_steps.rb:244:in `/^cookie "([^\"]*)" should be like "([^\"]*)"$/'
features/auth.feature:57:in `And cookie "go" should be like "change"'
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.