Skip to content

validation_errors throws error when there are no errors #9

@happycollision

Description

@happycollision

If you invoke the validation_errors method when your response has no errors, you get an error. Which is about 5 hours worth of confusing.

Take the following as an example:

RSpec.describe "reservations#create", type: :request do
  subject(:make_request) do
    jsonapi_post "/api/v1/reservations", payload
  end

  describe 'basic create' do
    let!(:patron) { create(:patron) }
    let(:payload) do
      {
        data: {
          type: 'reservations',
          relationships: {
            patron: {
              data: { type: 'patrons', id: patron.id.to_s }
            }
          }
        }
      }
    end

    it 'creates the resource with valid params' do
      make_request
      expect(validation_errors).to be_empty
    end
  end
end

If your data is bad—like if I just omit the relationships part of the payload above—you get a helpful message:

1) reservations#create basic create creates the resource with valid params                                                  
     Failure/Error: expect(validation_errors).to be_empty      
       expected `{:patron=>"must exist"}.empty?` to return true, got false 

But once you have actual, valid data, you get this:

  1) reservations#create basic create creates the resource with valid params                                                  
     Failure/Error: expect(validation_errors).to be_empty      
                                                               
     NoMethodError:                                            
       undefined method `each' for nil:NilClass

If you write your test like this is passes just fine.

    it 'creates the resource with valid params' do
      make_request
      expect(json['errors']).to be_nil
    end

And just for grins, if you add one single line like this...

    it 'creates the resource with valid params' do
      make_request
      puts validation_errors
      expect(json['errors']).to be_nil
    end

Boom. Failure.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions