2011-10-17 36 views
3

我可以寫與cookies請求罰款:我如何測試rspec簽名或永久cookie?

request.cookies['foo'] = 'bar' 

但是,這些工作:

request.cookies.permanent['foo'] = 'bar' 
request.cookies.signed['foo'] = 'bar' 
request.cookies.permanent.signed['foo'] = 'bar' # what I really want 

我得到空的哈希信息像這樣的消息:

NoMethodError: 
    undefined method `signed' for {}:Hash 

如何我可以爲我的測試創建這些Cookie嗎?

我正在使用rails 3.1和rspec 2.6.0。

回答

1

假設你有以下Rails的助手:

module ApplicationHelper 
    def set_cookie(name, value) 
    cookies.permanent.signed[name] = value 
    end 
end 

的Rails 3.2.6測試這種使用RSpec的2.11.0,你可以做到以下幾點:

require 'spec_helper' 

describe ApplicationHelper do 
    it "should set a permanent, signed cookie" do 
    cookies.should_receive(:permanent).once.and_return(cookies) 
    cookies.should_receive(:signed).once.with(:user_id, 12345) 
    helper.set_cookie(:user_id, 12345) 
    end 
end 

我從來沒有遇到過使用rspec來測試cookies.signed[:foo].should == 'bar'的問題,但在打電話給cookies.permanent給了我過去的問題。上面,我真的只是剔除了permanent方法並再次返回cookies對象。這使我可以測試它已被調用。

你真的不應該擔心天氣軌道本身設置永久性cookie,因爲這已經被測試。

+1

故障/錯誤:response.cookies.should_receive(:永久).once.and_return(餅乾) NoMethodError: 未定義的方法'should_receive」爲#<哈希: 0x007ffe4dcf34d0> –

+0

必須啓用嘲諷 – bschaeffer

4

使用

cookies.permanent['foo'] = 'bar' 
cookies.signed['foo'] = 'bar' 
cookies.permanent.signed['foo'] = 'bar' 

相反