2011-03-29 100 views
19

helper方法Rspec的:在一個輔助測試設置cookie

# Determine if this is user's first time 
    def first_time? 
    cookies[:first_time].nil? 
    end 

試圖Rspec的測試

it "returns true if the cookie is set" do 
    cookies[:first_time] = "something" 
    helper.first_time?().should be(true) 
end 

錯誤:

undefined method `cookies' for nil:NilClass 

一切我讀過有關Rspec的餅乾有與控制器做。在Rspec助手測試中獲取/設置cookie的任何方式?

(Rspec的/ Rspec的護欄2.5,Rails的3.0.4)

謝謝!

UPDATE:

找到如何設置cookies的答案,所以我會在這裏把它留給其他的參考。

這塊我一直在尋找:

helper.request.cookies[:awesome] = "something" 

還是不知道怎麼弄餅乾...

+0

只是好奇,你爲什麼會想餅乾?在規格中,您始終是設置Cookie的人,所以您知道他們是什麼。你不是隻想測試一下你的應用程序是否以某種方式按照某種方式設置了cookies? – radixhound 2012-08-04 15:35:25

+0

GET只是'helper.request.cookies [:awesome]' – 2016-04-20 22:13:02

回答

17

我已經能夠找到的最好的解釋是在這裏:https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/cookies

報價:

Recommended guidelines for rails-3.0.0 to 3.1.0

  • Access cookies through the request and response objects in the spec.
  • Use request.cookies before the action to set up state.
  • Use response.cookies after the action to specify outcomes.
  • Use the cookies object in the controller action.
  • Use String keys.

例如:

# spec 
request.cookies['foo'] = 'bar' 
get :some_action 
response.cookies['foo'].should eq('modified bar') 

# controller 
def some_action 
    cookies['foo'] = "modified #{cookies['foo']}" 
end 
+0

還要注意,如果您使用像'cookies [:foo] = true'這樣的符號設置cookie,您將擁有密鑰並且值轉換爲字符串'cookies ['foo'] ='true'' – Calin 2013-10-28 14:07:03

0

你得到的cookies,您將它們設置相同的方式。從我的規格的一個例子:

request.cookies[:email].should be nil 
+1

奇怪。如果我把它放在我的幫助器規範中,我會得到「未定義的局部變量或方法'請求'」。如果我將它更改爲helper.request,我會得到零(儘管它在功能上工作正常,代碼也很實用)。哎呀。 – jmccartie 2011-04-01 04:14:01

+0

這裏是我試圖運行的規範及其結果:https://gist.github.com/897722 – jmccartie 2011-04-01 04:19:33

2

我只是偶然發現了你的問題(我正在尋找答案)。我想這成功:

helper.request.cookies[:foo] = "bar" 
0

在控制器測試工作的:

@request.cookies[:cookie_name] = "cookie_value" 

塊之前。

我發現這個here