|
| 1 | +require 'spec_helper' |
| 2 | +require 'grape-active_model_serializers/error_formatter' |
| 3 | + |
| 4 | +describe Grape::ErrorFormatter::ActiveModelSerializers do |
| 5 | + subject { Grape::ErrorFormatter::ActiveModelSerializers } |
| 6 | + let(:backtrace) { ['Line:1'] } |
| 7 | + let(:options) { Hash.new } |
| 8 | + let(:env) { { 'api.endpoint' => app.endpoints.first } } |
| 9 | + let(:original_exception) { StandardError.new('oh noes!') } |
| 10 | + |
| 11 | + let(:app) { |
| 12 | + Class.new(Grape::API) do |app| |
| 13 | + app.format :json |
| 14 | + app.formatter :jsonapi, Grape::Formatter::ActiveModelSerializers |
| 15 | + app.error_formatter :jsonapi, Grape::ErrorFormatter::ActiveModelSerializers |
| 16 | + |
| 17 | + app.namespace('space') do |ns| |
| 18 | + ns.get('/', root: false) do |
| 19 | + error!(message) |
| 20 | + end |
| 21 | + end |
| 22 | + end |
| 23 | + } |
| 24 | + let(:foo) { |
| 25 | + Class.new { |
| 26 | + include ActiveModel::Model |
| 27 | + |
| 28 | + attr_accessor :name |
| 29 | + |
| 30 | + def initialize(attributes = {}) |
| 31 | + super |
| 32 | + errors.add(:name, 'We don\'t like bears') |
| 33 | + end |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + before do |
| 38 | + ActiveModel::Serializer.config.adapter = :json_api |
| 39 | + end |
| 40 | + |
| 41 | + after do |
| 42 | + ActiveModel::Serializer.config.adapter = :json |
| 43 | + end |
| 44 | + |
| 45 | + describe '#call' do |
| 46 | + context 'message is an activemodel' do |
| 47 | + let(:message) { |
| 48 | + foo.new(name: 'bar') |
| 49 | + } |
| 50 | + it 'formats the error' do |
| 51 | + result = subject |
| 52 | + .call(message, backtrace, options, env, original_exception) |
| 53 | + json_hash = JSON.parse(result) |
| 54 | + |
| 55 | + expected_result = { |
| 56 | + 'errors' => [ |
| 57 | + { |
| 58 | + 'source' => { |
| 59 | + 'pointer' => '/data/attributes/name' |
| 60 | + }, |
| 61 | + 'detail' => 'We don\'t like bears' |
| 62 | + } |
| 63 | + ] |
| 64 | + } |
| 65 | + |
| 66 | + expect(json_hash == expected_result).to eq(true) |
| 67 | + end |
| 68 | + end |
| 69 | + |
| 70 | + context 'message is hash like' do |
| 71 | + let(:message) { { 'errors' => ['error'] } } |
| 72 | + it 'passes the message through' do |
| 73 | + result = subject |
| 74 | + .call(message, backtrace, options, env, original_exception) |
| 75 | + json_hash = JSON.parse(result) |
| 76 | + |
| 77 | + expect(json_hash == message).to eq(true) |
| 78 | + end |
| 79 | + end |
| 80 | + |
| 81 | + context 'message is text' do |
| 82 | + let(:message) { 'error' } |
| 83 | + it 'wraps the error' do |
| 84 | + result = subject |
| 85 | + .call(message, backtrace, options, env, original_exception) |
| 86 | + json_hash = JSON.parse(result) |
| 87 | + |
| 88 | + expect(json_hash == { 'error' => message }).to eq(true) |
| 89 | + end |
| 90 | + end |
| 91 | + end |
| 92 | +end |
0 commit comments