2012-10-29 29 views
0

我想測試一下,如果我的Rails控制器爲cookie設置有效選項(本例中爲path)。我怎麼能用RSpec做到這一點?rspec:測試cookie選項

我的代碼:

#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 

回答

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 
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 
+0

我愛你<3。這樣你就可以在rails中測試cookie的到期日期。 –