Class: ShouldaExt::Matchers::RespondWithJsonMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/shoulda_ext/matchers/respond_with_json.rb

Instance Method Summary collapse

Constructor Details

#initialize(context, description = nil, &block) ⇒ RespondWithJsonMatcher

Returns a new instance of RespondWithJsonMatcher.



37
38
39
40
41
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 37

def initialize(context, description = nil, &block)
  @block = block || lambda{|*| true }
  @description = description
  @exactly = false
end

Instance Method Details

#descriptionObject



56
57
58
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 56

def description
  @description ||= "respond with JSON"
end

#errorsObject



68
69
70
71
72
73
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 68

def errors
  @errors = []
  @errors << 'Failed to parse the response as JSON' unless @parsable
  @errors << "Failed to #{'exactly ' if @exactly}match json: expected #{@exactly ? @expected_value.inspect : true}, but found #{@exactly ? @response_json.inspect : @block_result} " unless @json_matched
  @errors
end

#exactly(expected_json = nil, &block) ⇒ Object

Provide an exact result directly or using a block argument



44
45
46
47
48
49
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 44

def exactly(expected_json = nil, &block)
  @exactly = true
  @expected_value = expected_json
  @block = block
  self
end

#failure_messageObject



60
61
62
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 60

def failure_message
  "Expected to respond with json, but: #{errors.join("\n")}"
end

#in_context(context) ⇒ Object



51
52
53
54
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 51

def in_context(context)
  @context = context
  self
end

#json_matched?Boolean

Returns:

  • (Boolean)


75
76
77
78
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 75

def json_matched?
  @expected_value ||= run_block
  @json_matched ||= @exactly ? @response_json == @expected_value : !!@block_result
end

#matches?(subject) ⇒ Boolean

Returns:

  • (Boolean)


91
92
93
94
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 91

def matches?(subject)
  @subject = subject
  parsable? and json_matched?
end

#negative_failure_messageObject



64
65
66
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 64

def negative_failure_message
  "Expected not to respond with json, but: #{errors.join("\n")}"
end

#parsable?Boolean

Returns:

  • (Boolean)


84
85
86
87
88
89
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 84

def parsable?
  @parsable = true
  @response_json = JSON.parse(@subject.response.body)
rescue
  @parsable = false
end

#run_blockObject



80
81
82
# File 'lib/shoulda_ext/matchers/respond_with_json.rb', line 80

def run_block
  @block_result = @context.instance_exec(@response_json, &@block)
end