jmccartie
jmccartie

Reputation: 4976

Rspec: setting cookies in a helper test

Helper Method

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

Attempted Rspec test

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

Error:

undefined method `cookies' for nil:NilClass

Everything I've read about Rspec and cookies has to do with the controller. Any way to get/set cookies in Rspec helper tests?

(Rspec/Rspec-rails 2.5, Rails 3.0.4)

Thanks!!

UPDATE:

Found an answer on how to SET cookies, so I'll leave it here for other's reference.

the piece I was looking for:

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

Still don't know how to GET cookies...

Upvotes: 28

Views: 21312

Answers (5)

Alexander
Alexander

Reputation: 4237

None of the answers worked for me on Rails 6.1.3, but after much testing, the following worked:

helper.cookies[:foo] = "bar"

And for signed cookies:

helper.cookies.signed[:foo] = "bar"

Upvotes: 4

MERM
MERM

Reputation: 752

In a controller test this works:

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

in a before block.

I found this here

Upvotes: 0

apneadiving
apneadiving

Reputation: 115511

I just stumbled upon your question (I was looking for an answer). I tried this successfully:

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

Upvotes: 6

iwasrobbed
iwasrobbed

Reputation: 46703

The best explanation I've been able to find is here: https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/cookies

Quoted:

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.

Example:

# 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

Upvotes: 22

user100766
user100766

Reputation:

You get the cookies the same way you set them. Example from one of my specs:

request.cookies[:email].should be nil

Upvotes: 0

Related Questions