File: have_received.rb

package info (click to toggle)
ruby-rspec-mocks 2.14.5-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 868 kB
  • ctags: 725
  • sloc: ruby: 8,227; makefile: 4
file content (93 lines) | stat: -rw-r--r-- 2,350 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
module RSpec
  module Mocks
    module Matchers
      class HaveReceived
        COUNT_CONSTRAINTS = %w(exactly at_least at_most times once twice)
        ARGS_CONSTRAINTS = %w(with)
        CONSTRAINTS = COUNT_CONSTRAINTS + ARGS_CONSTRAINTS

        def initialize(method_name)
          @method_name = method_name
          @constraints = []
          @subject = nil
        end

        def matches?(subject)
          @subject = subject
          @expectation = expect
          expected_messages_received?
        end

        def does_not_match?(subject)
          @subject = subject
          ensure_count_unconstrained
          @expectation = expect.never
          expected_messages_received?
        end

        def failure_message
          generate_failure_message
        end

        def negative_failure_message
          generate_failure_message
        end

        def description
          expect.description
        end

        CONSTRAINTS.each do |expectation|
          define_method expectation do |*args|
            @constraints << [expectation, *args]
            self
          end
        end

        private

        def expect
          expectation = mock_proxy.build_expectation(@method_name)
          apply_constraints_to expectation
          expectation
        end

        def apply_constraints_to(expectation)
          @constraints.each do |constraint|
            expectation.send(*constraint)
          end
        end

        def ensure_count_unconstrained
          if count_constraint
            raise RSpec::Mocks::MockExpectationError,
              "can't use #{count_constraint} when negative"
          end
        end

        def count_constraint
          @constraints.map(&:first).detect do |constraint|
            COUNT_CONSTRAINTS.include?(constraint)
          end
        end

        def generate_failure_message
          mock_proxy.check_for_unexpected_arguments(@expectation)
          @expectation.generate_error
        rescue RSpec::Mocks::MockExpectationError => error
          error.message
        end

        def expected_messages_received?
          mock_proxy.replay_received_message_on @expectation
          @expectation.expected_messages_received?
        end

        def mock_proxy
          RSpec::Mocks.proxy_for(@subject)
        end
      end
    end
  end
end