Skip to content

Commit fa70e86

Browse files
committed
Simplify the way we explain how to test cookies in controller
The previous documentation was old and was not clear enough to help developers to understand properly how to test cookies inside a controller test. Since then it is much easier to test cookies if you stick to `cookies` and don't use `response.cookies`. You can use response.cookies when you don't change cookies inside your test. ``` def show cookies["user_name"] = nil head 200 end RSpec.describe SignOutsController, type: :request do describe 'GET /signout' do it "clear cookie value" do get "/sign_out" expect(response.cookies["user_name"]).to eq(nil) end end end ``` Use `cookies` to set and expect when you set cookies inside your test ``` def show cookies.delete("user_name") head 200 end RSpec.describe SignOutsController, type: :request do describe 'GET /signout' do it "clear cookie value" do cookies["user_name"] = "Sam" get "/sign_out" expect(cookies["user_name"]).to eq("") end end end ``` This is the prefered way and this is way it is documented like that. Related: - #1993
1 parent f970835 commit fa70e86

File tree

2 files changed

+36
-56
lines changed

2 files changed

+36
-56
lines changed

features/controller_specs/Cookies.md

Lines changed: 0 additions & 56 deletions
This file was deleted.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Feature: Cookies
2+
3+
There is different ways to test cookies in controller's tests be we recommend
4+
to use `cookies` as below.
5+
6+
You can use strings or symbols to fetch or set your cookies because `cookies`
7+
support indifferent access.
8+
9+
Scenario: Testing cookie's value cleared in controller
10+
Given a file named "spec/controllers/application_controller_spec.rb" with:
11+
"""ruby
12+
require "rails_helper"
13+
14+
RSpec.describe ApplicationController, :type => :controller do
15+
controller do
16+
def clear_cookie
17+
cookies.delete(:user_name)
18+
head :ok
19+
end
20+
end
21+
22+
before do
23+
routes.draw { get "clear_cookie" => "anonymous#clear_cookie" }
24+
end
25+
26+
it "clear cookie's value 'user_name'" do
27+
cookies[:user_name] = "Sam"
28+
29+
get :clear_cookie
30+
31+
expect(cookies[:user_name]).to eq nil
32+
end
33+
end
34+
"""
35+
When I run `rspec spec`
36+
Then the example should pass

0 commit comments

Comments
 (0)