ruby-grape / ruby-grape/grape

Error when validating array items with different conditionally required properties

Open
#2,473 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug?
Dominant language
Ruby
Stars
10k
Forks
1.2k
Avg merge
14h 38m
Merged PRs (30d)
92

Description

Hello,

If we define different properties required for array items by given condition then validation fails even if correct request is sent.

Please check the example below:

it 'test to demonstrate the validation issue' do
  subject.params do
    requires :a, type: String, allow_blank: false, values: %w[x y z]
    given a: ->(val) { val == 'z' } do
      requires :inner3, type: Array, allow_blank: false do
        requires :bar, type: String, allow_blank: false

        given bar: ->(val) { val == 'b' } do
          requires :baz, type: Array do
            requires :new_category, type: String
          end
        end

        given bar: ->(val) { val == 'c' } do
          requires :baz, type: Array do
            requires :baz_category, type: String
          end
        end

      end
    end
  end
  subject.post('/nested-dependency') { declared(params).to_json }

  test = {
    a: 'z',
    inner3: [
      { bar: 'b', baz: [{ new_category: 'nope' }] },
      { bar: 'c', baz: [{ baz_category: 'nope' }] }
    ]
  }

  post '/nested-dependency', **test

  expect(last_response.status).to eq(200)
end

Expected behavior: 200 OK

Actual behavior: 400 Bad request, "inner3[1][baz][0][new_category] is missing, inner3[1][baz][0][baz_category] is missing"

Thank you.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the supplied nested-dependency example, starting with the subject.params declaration and the nested subject.post request shown in the issue. Trace validation of array items whose bar values select different required properties. Done means the request returns 200 and a regression test confirms that new_category is required only for bar 'b' while baz_category is required only for bar 'c'.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
api
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.