|
| 1 | +require 'spec_helper' |
| 2 | + |
| 3 | +describe Grape::Parser do |
| 4 | + subject { described_class } |
| 5 | + |
| 6 | + describe '.builtin_parsers' do |
| 7 | + it 'returns an instance of Hash' do |
| 8 | + expect(subject.builtin_parsers).to be_an_instance_of(Hash) |
| 9 | + end |
| 10 | + |
| 11 | + it 'includes json and xml parsers by default' do |
| 12 | + expect(subject.builtin_parsers).to include(json: Grape::Parser::Json, xml: Grape::Parser::Xml) |
| 13 | + end |
| 14 | + end |
| 15 | + |
| 16 | + describe '.parsers' do |
| 17 | + it 'returns an instance of Hash' do |
| 18 | + expect(subject.parsers({})).to be_an_instance_of(Hash) |
| 19 | + end |
| 20 | + |
| 21 | + it 'includes built-in parsers' do |
| 22 | + expect(subject.parsers({})).to include(subject.builtin_parsers) |
| 23 | + end |
| 24 | + |
| 25 | + context 'with :parsers option' do |
| 26 | + let(:parsers) { { customized: Class.new } } |
| 27 | + it 'includes passed :parsers values' do |
| 28 | + expect(subject.parsers(parsers: parsers)).to include(parsers) |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + context 'with added parser by using `register` keyword' do |
| 33 | + let(:added_parser) { Class.new } |
| 34 | + before { subject.register :added, added_parser } |
| 35 | + it 'includes added parser' do |
| 36 | + expect(subject.parsers({})).to include(added: added_parser) |
| 37 | + end |
| 38 | + end |
| 39 | + end |
| 40 | + |
| 41 | + describe '.parser_for' do |
| 42 | + let(:options) { {} } |
| 43 | + |
| 44 | + it 'calls .parsers' do |
| 45 | + expect(subject).to receive(:parsers).with(options).and_return(subject.builtin_parsers) |
| 46 | + subject.parser_for(:json, options) |
| 47 | + end |
| 48 | + |
| 49 | + it 'returns parser correctly' do |
| 50 | + expect(subject.parser_for(:json)).to eq(Grape::Parser::Json) |
| 51 | + end |
| 52 | + |
| 53 | + context 'when parser is available' do |
| 54 | + before { subject.register :customized_json, Grape::Parser::Json } |
| 55 | + it 'returns registered parser if available' do |
| 56 | + expect(subject.parser_for(:customized_json)).to eq(Grape::Parser::Json) |
| 57 | + end |
| 58 | + end |
| 59 | + |
| 60 | + context 'when parser is an instance of Symbol' do |
| 61 | + before do |
| 62 | + allow(subject).to receive(:foo).and_return(:bar) |
| 63 | + subject.register :foo, :foo |
| 64 | + end |
| 65 | + |
| 66 | + it 'returns an instance of Method' do |
| 67 | + expect(subject.parser_for(:foo)).to be_an_instance_of(Method) |
| 68 | + end |
| 69 | + |
| 70 | + it 'returns object which can be called' do |
| 71 | + method = subject.parser_for(:foo) |
| 72 | + expect(method.call).to eq(:bar) |
| 73 | + end |
| 74 | + end |
| 75 | + |
| 76 | + context 'when parser does not exist' do |
| 77 | + it 'returns nil' do |
| 78 | + expect(subject.parser_for(:undefined)).to be_nil |
| 79 | + end |
| 80 | + end |
| 81 | + end |
| 82 | +end |
0 commit comments