Skip to content

Commit

Permalink
Add tests for returning a 415 when content type isn't supported
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh Murphy committed Jun 5, 2018
1 parent d571f25 commit d2e2f7e
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions spec/grape/middleware/formatter_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'spec_helper'
require 'pry'

describe Grape::Middleware::Formatter do
subject { Grape::Middleware::Formatter.new(app) }
Expand Down Expand Up @@ -224,6 +225,80 @@ def to_xml

context 'input' do
%w[POST PATCH PUT DELETE].each do |method|
context 'when body is not nil or empty' do
context 'when Content-Type is supported' do
let(:io) { StringIO.new('{"is_boolean":true,"string":"thing"}') }
let(:content_type) { 'application/json' }

it "parses the body from #{method} and copies values into rack.request.form_hash" do
subject.call(
'PATH_INFO' => '/info',
'REQUEST_METHOD' => method,
'CONTENT_TYPE' => content_type,
'rack.input' => io,
'CONTENT_LENGTH' => io.length
)
expect(subject.env['rack.request.form_hash']['is_boolean']).to be true
expect(subject.env['rack.request.form_hash']['string']).to eq('thing')
end
end

context 'when Content-Type is not supported' do
let(:io) { StringIO.new('{"is_boolean":true,"string":"thing"}') }
let(:content_type) { 'application/atom+xml' }

it 'returns a 415 HTTP error status' do
error = catch(:error) {
subject.call(
'PATH_INFO' => '/info',
'REQUEST_METHOD' => method,
'CONTENT_TYPE' => content_type,
'rack.input' => io,
'CONTENT_LENGTH' => io.length
)
}
expect(error[:status]).to eq(415)
expect(error[:message]).to eq("The requested content-type 'application/atom+xml' is not supported.")
end
end
end

context 'when body is nil' do
let(:io) { double }
before do
allow(io).to receive_message_chain(:rewind, :read).and_return(nil)
end

it 'does not read and parse the body' do
expect(subject).not_to receive(:read_rack_input)
subject.call(
'PATH_INFO' => '/info',
'REQUEST_METHOD' => method,
'CONTENT_TYPE' => 'application/json',
'rack.input' => io,
'CONTENT_LENGTH' => 0
)
end
end

context 'when body is empty' do
let(:io) { double }
before do
allow(io).to receive_message_chain(:rewind, :read).and_return('')
end

it 'does not read and parse the body' do
expect(subject).not_to receive(:read_rack_input)
subject.call(
'PATH_INFO' => '/info',
'REQUEST_METHOD' => method,
'CONTENT_TYPE' => 'application/json',
'rack.input' => io,
'CONTENT_LENGTH' => 0
)
end
end

['application/json', 'application/json; charset=utf-8'].each do |content_type|
context content_type do
it "parses the body from #{method} and copies values into rack.request.form_hash" do
Expand Down

0 comments on commit d2e2f7e

Please sign in to comment.