1 | module Mocks
|
---|
2 | module TestDouble
|
---|
3 | # attr_reader :mocks
|
---|
4 | def initialize
|
---|
5 | $_mruby_mock_expectations ||= { }
|
---|
6 | end
|
---|
7 |
|
---|
8 | def self.extended(instance)
|
---|
9 | instance.instance_eval do
|
---|
10 | def method_missing(name, *args, &block)
|
---|
11 | if $_mruby_mock_expectations[self]
|
---|
12 | $_mruby_mock_expectations[self][name][:invoked] = true
|
---|
13 |
|
---|
14 | hash = { :expected_args => $_mruby_mock_expectations[self][name][:with] == args }
|
---|
15 | hash[:expected_args] = true if args.empty? && $_mruby_mock_expectations[self][name][:with].nil?
|
---|
16 | hash[:args] = args
|
---|
17 | $_mruby_mock_expectations[self][name][:history] << hash
|
---|
18 |
|
---|
19 | return $_mruby_mock_expectations[self][name][:returns]
|
---|
20 | else
|
---|
21 | super
|
---|
22 | end
|
---|
23 | end
|
---|
24 | end
|
---|
25 | end
|
---|
26 |
|
---|
27 | def stubs(method)
|
---|
28 | $_mruby_mock_expectations ||= { }
|
---|
29 | $_mruby_mock_expectations[self] ||= { }
|
---|
30 | $_mruby_mock_expectations[self][method] ||= Mocks::Expectation.new
|
---|
31 |
|
---|
32 | unless self.class == Mocks::Mock
|
---|
33 | self.class.class_eval do
|
---|
34 | if method_defined?(method)
|
---|
35 | alias_method "original_#{method}".to_sym, method
|
---|
36 | undef_method(method)
|
---|
37 | end
|
---|
38 | end
|
---|
39 | end
|
---|
40 | $_mruby_mock_expectations[self][method].add_stub(method)
|
---|
41 |
|
---|
42 | end
|
---|
43 |
|
---|
44 | def original_method(method)
|
---|
45 | self.send("original_#{method}")
|
---|
46 | end
|
---|
47 |
|
---|
48 | def method_missing(name, *args, &block)
|
---|
49 | if $_mruby_mock_expectations[self]
|
---|
50 | $_mruby_mock_expectations[self][name][:invoked] = true
|
---|
51 |
|
---|
52 | hash = { :expected_args => $_mruby_mock_expectations[self][name][:with] == args }
|
---|
53 | hash[:expected_args] = true if args.empty? && $_mruby_mock_expectations[self][name][:with].nil?
|
---|
54 | hash[:args] = args
|
---|
55 | $_mruby_mock_expectations[self][name][:history] << hash
|
---|
56 |
|
---|
57 | return $_mruby_mock_expectations[self][name][:returns]
|
---|
58 | else
|
---|
59 | super
|
---|
60 | end
|
---|
61 | end
|
---|
62 |
|
---|
63 | end
|
---|
64 |
|
---|
65 | end
|
---|
66 |
|
---|
67 | BasicObject.class_eval do
|
---|
68 | def mocks
|
---|
69 | mock = self.new.instance_eval { self.extend ::Mocks::TestDouble }
|
---|
70 | end
|
---|
71 | end
|
---|