rspec:测试cookie选项

时间:2012-10-29 15:28:05

标签: ruby-on-rails cookies rspec

我想测试我的Rails控制器是否为cookie设置了有效选项(在本例中为path)。我怎么能用RSpec做到这一点?

我的代码:

#Controller
def action
  #(...)
  cookies[:name] = { value:cookie_data,
                     path: cookie_path }
  #(...)
end

#spec 
it "sets cookie path" do
  get 'action'
  #I'd like do to something like that
  response.cookies['name'].path.should == '/some/path' 
end

2 个答案:

答案 0 :(得分:3)

尝试让CGI :: Cookie.parse做正确的事后尝试失败,我结束了自己的解析器。这很简单:

def parse_set_cookie_header(header)
  kv_pairs = header.split(/\s*;\s*/).map do |attr|
    k, v = attr.split '='

    [ k, v || nil ]
  end

  Hash[ kv_pairs ]
end

以下是它产生的结果的样本:

Cookie创建:

IN: "signup=VALUE_HERE; path=/subscriptions; secure; HttpOnly"
OUT: {"signup"=>"VALUE_HERE", "path"=>"/subscriptions", "secure"=>nil, "HttpOnly"=>nil}

Cookie删除:

IN: "signup=; path=/subscriptions; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000; secure; HttpOnly"
OUT: {"signup"=>nil, "path"=>"/subscriptions", "max-age"=>"0", "expires"=>"Thu, 01 Jan 1970 00:00:00 -0000", "secure"=>nil, "HttpOnly"=>nil}

以下是一个示例规范:

describe 'the Set-Cookie header' do
  let(:value) { 'hello world' }

  let(:signup_cookie) do
    parse_set_cookie_header response.header['Set-Cookie']
  end

  before do
    get :index, :spec => 'set_signup_cookie'
  end

  it 'has a payload set for :signup' do
    expect(signup_cookie['signup']).to be_present
  end

  it 'has the right path' do
    expect(signup_cookie['path']).to eq '/subscriptions'
  end

  it 'has the secure flag set' do
    expect(signup_cookie).to have_key 'secure'
  end

  it 'has the HttpOnly flag set' do
    expect(signup_cookie).to have_key 'HttpOnly'
  end

  it 'is a session cookie (i.e. it has no :expires)' do
    expect(signup_cookie).not_to have_key 'expires'
  end

  it 'has no max-age' do
    expect(signup_cookie).not_to have_key 'max-age'
  end
end

答案 1 :(得分:0)

我找到了一个解决方案,但它似乎是一种黑客行为。我想知道是否有更清洁的方法。

it "sets cookie path" do
  get 'action'
  match = response.header["Set-Cookie"].match(/path=(.*);?/)
  match.should_not be_nil
  match[1].should == '/some/path'
end