Class: Cybertrain::Test::ClientCookies

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/test/client.rb

Overview

A Client’s cookie jar: each cookie’s raw (still percent-encoded) value by name, as the Set-Cookie headers so far left it. A name may be given as a String or a Symbol (cookies[:user] is cookies["user"], as in Rails’ integration tests). A cookie whose Max-Age or Expires has passed under Clock (so also after travel_to past it) is gone: not read, not listed, not sent, as a browser (and Rack::Test) would. A cookie a test writes with []= has no lifetime.

Examples:

client.get("/login")
client.cookies[:user]            # => "alice+smith"
client.cookies["theme"] = "dark"

Instance Method Summary collapse

Instance Method Details

#[](name) ⇒ String?

The cookie’s raw value, nil when there is none (or it expired).

Parameters:

  • name (String, Symbol)

Returns:

  • (String, nil)


153
154
155
156
157
158
# File 'cybertrain/test/client.rb', line 153

def [](name)
  key = name.to_s
  return nil unless jar_live?(key)

  @jar_values[key]
end

#[]=(name, value) ⇒ String

Sets a cookie for the next requests (raw: percent-encode it as a server would), with no lifetime.

Parameters:

  • name (String, Symbol)
  • value (String)

Returns:

  • (String)


166
167
168
# File 'cybertrain/test/client.rb', line 166

def []=(name, value)
  jar_store(name.to_s, value.to_s, -1)
end

#delete(name) ⇒ String?

Removes the cookie; answers the value it had (nil when none).

Parameters:

  • name (String, Symbol)

Returns:

  • (String, nil)


182
183
184
185
186
187
188
# File 'cybertrain/test/client.rb', line 182

def delete(name)
  key = name.to_s
  live = jar_live?(key)
  @jar_expires.delete(key)
  value = @jar_values.delete(key)
  live ? value : nil
end

#empty? ⇒ Boolean

Whether no cookie is there.

Returns:

  • (Boolean)


209
210
211
# File 'cybertrain/test/client.rb', line 209

def empty?
  keys.empty?
end

#key?(name) ⇒ Boolean

Whether the cookie is there (and not expired).

Parameters:

  • name (String, Symbol)

Returns:

  • (Boolean)


174
175
176
# File 'cybertrain/test/client.rb', line 174

def key?(name)
  jar_live?(name.to_s)
end

#keys ⇒ Array<String>

The names of the cookies there, in the order they were first set.

Returns:

  • (Array<String>)


193
194
195
196
197
# File 'cybertrain/test/client.rb', line 193

def keys
  names = Array.new(0) { "" }
  @jar_values.each_key { |key| names << key if jar_live?(key) }
  names
end

#size ⇒ Integer

How many cookies are there.

Returns:



202
203
204
# File 'cybertrain/test/client.rb', line 202

def size
  keys.length
end

#to_h ⇒ Hash{String => String}

The cookies as a Hash, name to raw value.

Returns:

  • (Hash{String => String})


216
217
218
219
220
221
# File 'cybertrain/test/client.rb', line 216

def to_h
  out = { "" => "" }
  out.delete("")
  keys.each { |key| out[key] = @jar_values[key].to_s }
  out
end