14

I'm trying to pass a cookie when doing a GET request, using rspec 2 and rails 3.

I've tried the following so far.

get "/", {}, {"Cookie" => "uuid=10"} # cookies[:uuid] is nil
request.cookies[:uuid] = 10 # request is nil
@request.env["Cookie"] = "uuid=10" # @request is nil
helper.request.cookies[:uuid] # helper is not defined
cookies[:uuid] = 10 # cookies[:uuid] is nil
controller.cookies[:uuid] = 10 # cookies is nil

Is it possible?

Linus Oleander
  • 17,746
  • 15
  • 69
  • 102

6 Answers6

8

Per this answer, you can use the cookies method within request specs:

before { cookies['foo'] = 'bar' }

I tried @phoet's solution involving ActionDispatch::Request.any_instance.stubs, but it throws an error along with a seemingly unrelated deprecation message in RSpec 3.4.

Community
  • 1
  • 1
Chris Peters
  • 17,918
  • 6
  • 49
  • 65
8

What works for me in RSpec Request tests is passing the HTTP Cookie header explicitly:

  before do
    get "/api/books", headers: { Cookie: "auth=secret" }
  end
jonne
  • 305
  • 3
  • 5
5

I was a little confused by how you did this at first, but it's actually really easy. Inside of Rails's ActionDispatch::IntegrationTest (or in rspec's case a :request spec) you have access to a cookies variable.

It works like this:

# set up your cookie
cookies["fruits"] = ["apple", "pear"]

# hit your endpoint
get fruits_path, {}, {}

# this works!
expect(cookies["fruits"]).to eq(["apple", "pear"])
andrewmarkle
  • 221
  • 3
  • 9
4

i had a similar issue and i did not find a proper solution to this.

the rspec-rails docs state that it should be possible:

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

in my spec request is always nil before executing a get.

i am now mocking the cookies:

before { ActionDispatch::Request.any_instance.stubs(cookies: {locale: :en}) }

this guy has a similar problem.

phoet
  • 18,688
  • 4
  • 46
  • 74
  • 2
    The docs you link to are for controller specs, not request specs, which is why `request` returns `nil`. Also trying to figure out how to do this in RSpec 3.4. – Chris Peters Jun 15 '16 at 13:39
4

In spec/requests/some_spec.rb you can use Rack::Test::Methods to set and read cookies.

describe 'Something' do

  include Rack::Test::Methods

  it 'can set cookies' do
    set_cookie "foo=red"
    post '/some/endpoint', params, headers
    expect(last_request.cookies[:foo]).to eq('red')
  end

end

Documentation:
http://www.rubydoc.info/github/brynary/rack-test/Rack/MockSession#set_cookie-instance_method

Jan Werkhoven
  • 2,656
  • 1
  • 22
  • 31
0

I got your case. In my case, I need the _sid from cookies in the controller request.cookies['_sid']

I fixed by

before do
  @request.cookies['_sid'] = sid
  get :show, id: job_id
end

it works for me.

so in your case, you can have a try.

before do
  @request.cookies[:uuid]
  get "/", {}
end
TorvaldsDB
  • 766
  • 9
  • 8