Skip to content

Commit 45ab4a6

Browse files
committed
Added the error matcher.
1 parent 0fa181a commit 45ab4a6

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ Available matchers:
4646
* `expect(document).to have_meta('foo' => 'bar', 'fum' => 'baz').exactly`
4747
* `expect(document).to have_jsonapi_object`
4848
* `expect(document).to have_jsonapi_object('version' => '1.0')`
49+
* `expect(document).to have_error('status' => '422')`
4950

5051
### On matcher arguments...
5152

lib/jsonapi/rspec.rb

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
require 'jsonapi/rspec/links'
99
require 'jsonapi/rspec/meta'
1010
require 'jsonapi/rspec/jsonapi_object'
11+
require 'jsonapi/rspec/errors'
1112

1213
RSpec.configure do |c|
1314
c.add_setting :jsonapi_indifferent_hash, default: false

lib/jsonapi/rspec/errors.rb

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module JSONAPI
2+
module RSpec
3+
module Meta
4+
::RSpec::Matchers.define :have_error do |error|
5+
match do |actual|
6+
actual = JSONAPI::RSpec.as_indifferent_hash(actual)
7+
return false unless actual.key?('errors')
8+
return false unless actual['errors'].is_a?(Array)
9+
10+
return true if actual['errors'].any? && error.nil?
11+
12+
error = JSONAPI::RSpec.as_indifferent_hash(error)
13+
14+
actual['errors'].any? { |actual_error| error <= actual_error }
15+
end
16+
end
17+
end
18+
end
19+
end

spec/jsonapi/errors_spec.rb

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
require 'spec_helper'
2+
3+
RSpec.describe JSONAPI::RSpec, '#have_error' do
4+
let(:doc) do
5+
{
6+
'errors' => [
7+
{
8+
'status' => '422',
9+
'source' => { 'pointer' => '/data/attributes/firstName' },
10+
'title' => 'Invalid Attribute',
11+
'detail' => 'First name must contain at least three characters.'
12+
}
13+
]
14+
}
15+
end
16+
17+
context 'when providing no value' do
18+
it 'succeeds when errors are present' do
19+
expect(doc).to have_error
20+
end
21+
22+
it 'fails when errors are missing' do
23+
expect({}).not_to have_error
24+
expect({ 'errors' => [] }).not_to have_error
25+
end
26+
end
27+
28+
context 'when providing a value' do
29+
it do
30+
expect(doc).to have_error(
31+
'status' => '422',
32+
'source' => { 'pointer' => '/data/attributes/firstName' }
33+
)
34+
end
35+
36+
it 'fails when meta is absent' do
37+
expect(doc).not_to have_error({ 'status' => '500' })
38+
end
39+
end
40+
end

0 commit comments

Comments
 (0)