2012-10-22 59 views
7

當我登錄到我的應用程序服務器發送我回餅乾(證書和一些應用程序的Cookie):測試響應餅乾

Response sent 170 bytes of Cookie data: 
Set-Cookie: user_credentials=val; path=/; HttpOnly; Secure 

Response sent 554 bytes of Cookie data: 
Set-Cookie: _app_session=otherVal; path=/; HttpOnly; Secure 

...,然後重定向到主頁;

Cookie包含一些標誌:例如: httpOnly,Secure

如何測試cookies是否包含Rspec的標誌?

至少在哪裏可以找到這些餅乾?

it "should generate cookies with proper flags" do  
    params = Factory.attributes_for(:user, 
     :username => "uname", 
     :password => "upass" 
    ) 
    # login 
    post 'create', params 

    response.should redirect_to home_url # => pass 

    puts "response cookie = #{response.cookies.inspect}" # => {} // no cookies in response, why? 
end 

回答

6

控制器規格不產生/調用真正 HTTP請求,他們只是下設測試控制器並調用它的請求的操作。沒有http請求,並且沒有real生成了http答案。所以你只能在更抽象的層次上測試Rails控制器的內部工作。

在這些規範的cookie處理是相當簡單的,在這樣一個動作設置cookie:

def set_cookies 
    cookies[:foo] = 'bar' 
    cookies[:lorem] = {:value => 'ipsum', :expires => 3.days.from_now} 

    render :nothing => true 
end 

結果如下值規範可訪問:

it "should set some cookie values" do 
    get :set_cookies 

    # response.cookies looks like this: 
    # {'foo' => 'bar', 'lorem' => 'ipsum'}  

    response.cookies['foo'].should == 'bar' 
    response.cookies['lorem'].should == 'ipsum' 
end 

要測試的樣的cookie標誌,你在你的回覆中看到的,你將不得不使用real http請求。也許你可以使用它的水豚寶石?

+0

嗯..其實'水豚'是超出我的工作範圍,但仍然謝謝; – ted

+0

餅乾怎麼設置呢?你是否在控制器中這樣做? – severin

+0

其中一個是由'Authlogic'創建的,另一個是'ActionController',我相信 – ted