summaryrefslogtreecommitdiff
path: root/test/support/assert_responses.rb
blob: 19c2768dd3c58b3759ea510db5639de7ad68221a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
module AssertResponses

  # response that works with different TestCases:
  # ActionController::TestCase has @response
  # ActionDispatch::IntegrationTest has @response
  # Rack::Test::Methods defines last_response
  def get_response
    @response || last_response
  end

  def content_type
    get_response.content_type.to_s.split(';').first
  end

  def json_response
    return nil unless content_type == 'application/json'
    response = JSON.parse(get_response.body)
    response.respond_to?(:with_indifferent_access) ?
      response.with_indifferent_access :
      response
  end

  def assert_text_response(body = nil)
    assert_equal 'text/plain', content_type
    unless body.nil?
      assert_equal body, get_response.body
    end
  end

  def assert_json_response(object)
    assert_equal 'application/json', content_type
    if object.is_a? Hash
      object.stringify_keys! if object.respond_to? :stringify_keys!
      assert_equal object, json_response
    else
      assert_equal object.to_json, get_response.body
    end
  end

  def assert_json_error(object)
    object.stringify_keys! if object.respond_to? :stringify_keys!
    assert_json_response :errors => object
  end

  # checks for the presence of a key in a json response
  # or a string in a text response
  def assert_response_includes(string_or_key)
    response = json_response || get_response.body
    assert response.include?(string_or_key),
      "response should have included #{string_or_key}"
  end

  def assert_attachement_filename(name)
    assert_equal %Q(attachment; filename="#{name}"),
      get_response.headers["Content-Disposition"]
  end

end

class ::ActionController::TestCase
  include AssertResponses
end

class ::ActionDispatch::IntegrationTest
  include AssertResponses
end