Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/purple/responses/object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
class Purple::Responses::Object
attr_accessor :attributes

delegate :to_s, to: :attributes
delegate :to_s, :[], to: :attributes

def contain?(key)
attributes.key?(key)
attributes.key?(key.to_sym) || attributes.key?(key.to_s)
end
end
39 changes: 39 additions & 0 deletions spec/purple/responses/body_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
require 'spec_helper'
require 'json'

RSpec.describe Purple::Responses::Body do
let(:structure) do
{
name: String,
day: { type: Integer, optional: true }
}
end

context 'when optional field is missing' do
let(:body) { { name: 'John' }.to_json }
subject(:response) { described_class.new(structure:, response: nil).validate!(body, {}) }

it 'returns false for contain? on the missing field' do
expect(response.contain?(:day)).to eq(false)
expect(response.contain?('day')).to eq(false)
end

it 'raises NoMethodError when accessing the missing optional field' do
expect { response.day }.to raise_error(
NoMethodError,
"Optional field 'day' is not present in the response body. Use `contain?(:day)` to check its presence."
)
end
end

context 'when optional field is present' do
let(:body) { { name: 'John', day: 15 }.to_json }
subject(:response) { described_class.new(structure:, response: nil).validate!(body, {}) }

it 'allows access to the field and contain? returns true' do
expect(response.day).to eq(15)
expect(response.contain?(:day)).to eq(true)
expect(response.contain?('day')).to eq(true)
end
end
end