Sha256: 45e0924660299c9b2b6df8d5f9a35245013f094f3d860df6911e6d78ceb90515

Contents?: true

Size: 1.67 KB

Versions: 3

Compression:

Stored size: 1.67 KB

Contents

RSpec::Matchers.define :set_cookie do |name, expected_value, expected_expires_at|
  failure_message_for_should do
    "Expected #{expectation} got #{result}"
  end

  match do |subject|
    @headers = subject
    @expected_name = name
    @expected_value = expected_value
    @expected_expires_at = expected_expires_at
    extract_cookies
    find_expected_cookie
    parse_expiration
    parse_value
    parse_path
    ensure_cookie_set
    ensure_expiration_correct
    ensure_path_is_correct
  end

  def ensure_cookie_set
    expect(@value).to eq @expected_value
  end

  def ensure_expiration_correct
    expect(@expires_at).not_to be_nil
    expect(@expires_at).to be_within(100).of(@expected_expires_at)
  end

  def ensure_path_is_correct
    expect(@path).to eq '/'
  end

  def expectation
    "a cookie named #{@expected_name} with value #{@expected_value.inspect} expiring at #{@expected_expires_at.inspect}"
  end

  def extract_cookies
    @cookie_headers = @headers['Set-Cookie'] || []
    @cookie_headers = [@cookie_headers] if @cookie_headers.respond_to?(:to_str)
  end

  def find_expected_cookie
    @cookie = @cookie_headers.detect do |header|
      header =~ /^#{@expected_name}=[^;]*(;|$)/
    end
  end

  def parse_expiration
    if @cookie && result = @cookie.match(/; expires=(.*?)(;|$)/)
      @expires_at = Time.parse(result[1])
    end
  end

  def parse_path
    if @cookie && result = @cookie.match(/; path=(.*?)(;|$)/)
      @path = result[1]
    end
  end

  def parse_value
    if @cookie && result = @cookie.match(/=(.*?)(?:;|$)/)
      @value = result[1]
    end
  end

  def result
    if @cookie
      @cookie
    else
      @cookie_headers.join("; ")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
clearance-1.6.0 spec/support/cookies.rb
clearance-1.5.1 spec/support/cookies.rb
clearance-1.5.0 spec/support/cookies.rb