2011-03-29 1 views
19

도우미 방법RSpec에 : 헬퍼 테스트에서 쿠키를 설정

# 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 

오류 : 나는 RSpec에와 쿠키에 대해 읽은

undefined method `cookies' for nil:NilClass 

다에있다 컨트롤러로 할 수 있습니다. Rspec 도우미 테스트에서 쿠키를 가져 오거나 설정할 수있는 방법은 무엇입니까?

감사 (RSpec에/RSpec에 레일 2.5, 3.0.4 레일)!

UPDATE :

쿠키를 설정하는 방법에 대한 답을 발견 그래서의 다른 참조를 위해 여기두고 있습니다.

내가 찾던 조각 :

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

아직도 쿠키를 GET하는 방법을 모른다 ...

+0

왜 쿠키를 원하십니까? 사양에서 항상 쿠키를 설정하는 사람이므로 자신이 무엇인지 알 수 있습니다. 쿠키가 특정 방식으로 설정된 상태에서 앱이 특정 방식으로 작동하는지 테스트하려고하지 않습니까? – radixhound

+0

GET은 단지'helper.request.cookies [: awesome]' –

답변

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'와 같은 기호로 설정하면 키와 쿠키로 변환 된 값'cookies [ 'foo'] = 'true' – Calin

0

당신은 쿠키 당신이 그들을 설정 같은 방법으로 얻을. 내 사양 중 하나의 예 :

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

Strange입니다. 이를 도우미 스펙에 배치하면 "정의되지 않은 지역 변수 또는 메소드'요청 '이 발생합니다. helper.request로 변경하면 아무런 결과도 얻지 못합니다 (기능은 훌륭하지만 코드는 견고합니다). 아하. – jmccartie

+0

여기에 내가 실행하려고하는 스펙과 그 결과가 나와 있습니다 : https://gist.github.com/897722 – jmccartie

2

나는 당신의 질문에 비틀 거리며 (나는 대답을 찾고 있었다). 나는 성공적이 시도 :

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

을이 작품 컨트롤러 테스트에서 : 블록 전에에서

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

.

이 항목을 찾았습니다. here