RSPEC:测试Cookie选项



我想测试我的轨道控制器是否为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

尝试使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 Creation:

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

我找到了一个解决方案,但这似乎是一种黑客。我想知道是否有一种更干净的方法。

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

我尝试了此处和类似线程提供的几种解决方案。对我来说唯一效果很好的是检查固定的标题,类似的标题:

it 'expires cookie in 15 minutes' do
  travel_to(Date.new(2016, 10, 25))
  post 'favorites', params: { flavor: 'chocolate' }
  travel_back
  details = 'favorite=chocolate; path=/; expires=Tue, 25 Oct 2016 07:15:00 GMT; HttpOnly'
  expect(response.header['Set-Cookie']).to eq details
end

这有点脆弱,因为cookie的其他非关键属性可能会破坏此字符串。但这确实使您无法内部轨道,并让您一次检查几个属性。(注意到这是一个反模式的RSPEC!)

如果您只关心一个属性,则可以这样匹配:

  expect(response.header['Set-Cookie']).to match(
    /favorite=chocolate.*; expires=Tue, 25 Oct 2016 07:15:00 GMT/
  )

相关内容

最新更新