Skip to content

Commit

Permalink
Raise an error if JSON encoding adapters are missing
Browse files Browse the repository at this point in the history
  • Loading branch information
rsutphin authored and mislav committed Jun 27, 2011
1 parent 264492a commit f87ea6e
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/faraday/error.rb
Expand Up @@ -34,5 +34,7 @@ def inspect
class ConnectionFailed < ClientError; end
class ResourceNotFound < ClientError; end
class ParsingError < ClientError; end

class MissingDependency < StandardError; end
end
end
6 changes: 5 additions & 1 deletion lib/faraday/request/json.rb
Expand Up @@ -3,7 +3,11 @@ class Request::JSON < Request::UrlEncoded
self.mime_type = 'application/json'.freeze

class << self
attr_accessor :adapter
attr_writer :adapter

def adapter
@adapter or raise Error::MissingDependency, "No JSON adapter available. Install either activesupport or yajl-ruby."
end
end

# loads the JSON encoder either from yajl-ruby or activesupport
Expand Down
31 changes: 31 additions & 0 deletions test/request_middleware_test.rb
Expand Up @@ -42,6 +42,37 @@ def test_json_skips_encoding_for_strings
assert_equal '{"a":"b"}', response.body
end

def test_json_fails_with_useful_message_when_no_json_adapter_available
without_json_adapter do
expected_msg = "No JSON adapter available. Install either activesupport or yajl-ruby."
# assert_raise doesn't work to check the message (at least on 1.8.7)
begin
@conn.post('/echo', { :fruit => %w[apples oranges] }, 'content-type' => 'application/json')
fail "Exception not raised"
rescue Faraday::Error::MissingDependency => e
assert_equal expected_msg, e.message
end
end
end

def test_url_encoded_does_not_fail_when_no_json_adapter_available
without_json_adapter do
assert_nothing_raised {
@conn.post('/echo', { :fruit => %w[apples oranges] })
}
end
end

def without_json_adapter
original_adapter = Faraday::Request::JSON.adapter
Faraday::Request::JSON.adapter = nil
begin
yield
ensure
Faraday::Request::JSON.adapter = original_adapter
end
end

def test_url_encoded_no_header
response = @conn.post('/echo', { :fruit => %w[apples oranges] })
assert_equal 'application/x-www-form-urlencoded', response.headers['Content-Type']
Expand Down

0 comments on commit f87ea6e

Please sign in to comment.