File: instance_method_stasher_spec.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 (58 lines) | stat: -rw-r--r-- 1,703 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
require 'spec_helper'

module RSpec
  module Mocks
    describe InstanceMethodStasher do
      class ExampleClass
        def hello
          :hello_defined_on_class
        end
      end

      def singleton_class_for(obj)
        class << obj; self; end
      end

      it "stashes the current implementation of an instance method so it can be temporarily replaced" do
        obj = Object.new
        def obj.hello; :hello_defined_on_singleton_class; end;

        stashed_method = InstanceMethodStasher.new(singleton_class_for(obj), :hello)
        stashed_method.stash

        def obj.hello; :overridden_hello; end
        expect(obj.hello).to eql :overridden_hello

        stashed_method.restore
        expect(obj.hello).to eql :hello_defined_on_singleton_class
      end

      it "stashes private instance methods" do
        obj = Object.new
        def obj.hello; :hello_defined_on_singleton_class; end;
        singleton_class_for(obj).__send__(:private, :hello)

        stashed_method = InstanceMethodStasher.new(singleton_class_for(obj), :hello)
        stashed_method.stash

        def obj.hello; :overridden_hello; end
        stashed_method.restore
        expect(obj.send(:hello)).to eql :hello_defined_on_singleton_class
      end

      it "only stashes methods directly defined on the given class, not its ancestors" do
        obj = ExampleClass.new

        stashed_method = InstanceMethodStasher.new(singleton_class_for(obj), :hello)
        stashed_method.stash

        def obj.hello; :overridden_hello; end;
        expect(obj.hello).to eql :overridden_hello

        stashed_method.restore
        expect(obj.hello).to eql :overridden_hello
      end
    end
  end
end