Skip to content

should_set_cookie macro #86

rnewman57 opened this Issue Mar 6, 2010 · 2 comments

2 participants


While adding a feature to Clearance, I wrote this macro that might be generally useful to add to shoulda:

def should_set_cookie(name, value, should_expire_at)
  description = "set a '#{name}' cookie to '#{value}'"
  if should_expire_at
    description << " expiring at #{should_expire_at}"
    description << " with no expiration date (session cookie)"
  should description do
    assert_equal value, cookies[name]
    # the following statement may be redundant with the preceding one, but can't hurt
    assert_equal value, @response.cookies[name]
    # cookies and @response[cookies] don't give us the expire time, so we need to fish it out 'manually'
    set_cookie_headers = @response.headers['Set-Cookie']
    assert_not_nil set_cookie_headers, "@response.headers['Set-Cookie'] must not be nil"
    regex = /^#{name}=#{value}(;|$)/
    assert_contains set_cookie_headers, regex
    cookie = set_cookie_headers.find {|h| h =~ regex}
    regex = /; expires=(.*?)(;|$)/
    if should_expire_at
      assert_contains cookie, regex, "cookie does not contain an 'expires=' attribute"
      cookie =~ regex
      expires_at = Time.parse($1)
      assert_in_delta should_expire_at, expires_at, 10 # seconds -- arbitrary delta
      assert_does_not_contain cookie, regex, "cookie contains an 'expires=' attribute but it shouldn't"

similar in spirit to earlier issue (and patch) #49 , except that my version also checks cookie expiration times

thoughtbot, inc. member
gabebw commented Mar 19, 2012


This looks useful - can you file a pull request over at shoulda-matchers? That's where all of the "real code" lives now. Shoulda has become just a meta-gem that depends on that code.

-- Gabe

@gabebw gabebw closed this Mar 19, 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.