2012-02-10 109 views
6

我想在黄瓜一步获得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 

我怎样才能获得使用水豚黄瓜步骤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;

水豚1.1.2;

机架测试0.6.1。

回答

8

步骤定义

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 

这是非常详细了。

+0

您可以将其解压为自定义方法,例如https://github.com/cucumber/cucumber/wiki/Cucumber-Backgrounder#steps-within-steps--an-anti-pattern中所述(朝向结尾的部分)。 – juanrpozo 2013-05-25 10:58:55

2

这是我一步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 

下面是示例输出时测试失败:

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"' 
5

看来,硒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返回一个由 “名” 和 “价值” 的数组,所以我们需要一个额外的参考,提取cookie值。