我试图在Cucumber步骤中获取cookie值:
步骤定义
When /^I log in$/ do
# code to log in
end
Then /^cookies should be set$/ do
cookies[:author].should_not be_nil
end
控制器
class SessionsController < ApplicationController
def create
cookies[:author] = 'me'
redirect_to authors_path
end
end
但它不起作用:
结果
expected: not nil
got: nil
在RSpec示例中,一切正常:
控制器规格
require 'spec_helper'
describe SessionsController do
describe 'create' do
it 'sets cookies' do
post :create
cookies[:author].should_not be_nil
end
end
end
如何使用Capybara在Cucumber步骤中获取cookie值?
感谢。
Debian GNU / Linux 6.0.4;
Ruby 1.9.3;
Ruby on Rails 3.2.1;
黄瓜1.1.4;
Cucumber-Rails 1.2.1;
Capybara 1.1.2;
Rack-Test 0.6.1。
答案 0 :(得分:10)
步骤定义
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
然而,这仍然有效,我仍在寻找一种不那么冗长的方式。此外,我想知道如何在步骤定义中获取会话数据。
<强>更新强>
要获取会话数据,应执行以下操作:
步骤定义
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
这也很冗长。
答案 1 :(得分:6)
似乎Selenium API发生了变化。建议的解决方案不起作用,但我花了一些时间环顾四周,找到了解决方案。
要保存Cookie:
browser = Capybara.current_session.driver.browser.manage
browser.add_cookie :name => key, :value => val
阅读cookie:
browser = Capybara.current_session.driver.browser.manage
browser.cookie_named(key)[:value]
cookie_named返回一个由“name”和“value”组成的数组,因此我们需要额外的引用来提取cookie值。
答案 2 :(得分:3)
试试show_me_the_cookies
宝石
https://github.com/nruth/show_me_the_cookies
答案 3 :(得分:3)
这是我的步骤防御代码:
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
以下是测试失败时的输出示例:
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"'