|
1 | 1 | module JSONAPI |
2 | 2 | module RSpec |
3 | 3 | module Attributes |
4 | | - ::RSpec::Matchers.define :have_attribute do |attr| |
5 | | - match do |actual| |
6 | | - actual = JSONAPI::RSpec.as_indifferent_hash(actual) |
7 | | - @attributes_node = actual['attributes'] |
| 4 | + ::RSpec::Matchers.define :have_attribute do |attr_name| |
| 5 | + match do |doc| |
| 6 | + doc = JSONAPI::RSpec.as_indifferent_hash(doc) |
| 7 | + attributes_node = doc['attributes'] |
8 | 8 |
|
9 | | - return false unless @attributes_node |
| 9 | + return false unless attributes_node |
10 | 10 |
|
11 | | - @has_attribute = @attributes_node.key?(attr.to_s) |
12 | | - if @has_attribute && @should_match_value |
13 | | - @actual_value = @attributes_node[attr.to_s] |
| 11 | + @existing_attributes = attributes_node.keys |
| 12 | + @has_attribute = attributes_node.key?(attr_name.to_s) |
| 13 | + @actual = attributes_node[attr_name.to_s] |
14 | 14 |
|
15 | | - # Work nicely with diffable |
16 | | - @actual = @actual_value |
17 | | - @expected = @expected_value |
| 15 | + return @actual == @expected if @has_attribute && @should_match_value |
18 | 16 |
|
19 | | - return @actual == @expected |
20 | | - end |
21 | 17 | @has_attribute |
22 | 18 | end |
23 | 19 |
|
24 | 20 | chain :with_value do |expected_value| |
25 | 21 | @should_match_value = true |
26 | | - @expected_value = expected_value |
| 22 | + @expected = expected_value |
27 | 23 | end |
28 | 24 |
|
29 | 25 | description do |
30 | | - result = "have attribute #{attr.inspect}" |
31 | | - if @should_match_value |
32 | | - result << " with value #{@expected_value.inspect}" |
33 | | - end |
| 26 | + result = "have attribute #{attr_name.inspect}" |
| 27 | + result << " with value #{@expected.inspect}" if @should_match_value |
34 | 28 | result |
35 | 29 | end |
36 | 30 |
|
37 | | - failure_message do |_actual| |
38 | | - if @has_attribute |
39 | | - "expected `#{attr}` attribute " \ |
| 31 | + failure_message do |_doc| |
| 32 | + if @actual |
| 33 | + "expected `#{attr_name}` attribute " \ |
40 | 34 | "to have value `#{@expected}` but was `#{@actual}`" |
41 | 35 | else |
42 | | - "expected attributes to include `#{attr}`. " \ |
43 | | - "Actual attributes were #{@attributes_node.keys}" |
| 36 | + "expected attributes to include `#{attr_name}`. " \ |
| 37 | + "Actual attributes were #{@existing_attributes}" |
44 | 38 | end |
45 | 39 | end |
46 | 40 |
|
47 | 41 | diffable |
48 | | - attr_reader :actual, :expected |
49 | 42 | end |
50 | 43 |
|
51 | 44 | ::RSpec::Matchers.define :have_jsonapi_attributes do |*attrs| |
|
0 commit comments