File: stubba_example_test.rb

package info (click to toggle)
libmocha-ruby 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 944 kB
  • ctags: 1,384
  • sloc: ruby: 7,265; makefile: 4
file content (102 lines) | stat: -rw-r--r-- 2,338 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
94
95
96
97
98
99
100
101
102
require File.join(File.dirname(__FILE__), "..", "test_helper")
require 'mocha'

class Widget
  
  def model
    'original_model'
  end
    
  class << self
  
    def find(options)
      []
    end
  
    def create(attributes)
      Widget.new
    end
  
  end
  
end

module Thingy
  
  def self.wotsit
    :hoojamaflip
  end
  
end

class StubbaExampleTest < Test::Unit::TestCase
  
  def test_should_stub_instance_method
    widget = Widget.new
    widget.expects(:model).returns('different_model')
    assert_equal 'different_model', widget.model
  end
  
  def test_should_stub_module_method
    should_stub_module_method
  end
  
  def test_should_stub_module_method_again
    should_stub_module_method
  end
  
  def test_should_stub_class_method
    should_stub_class_method
  end
  
  def test_should_stub_class_method_again
    should_stub_class_method
  end
  
  def test_should_stub_instance_method_on_any_instance_of_a_class
    should_stub_instance_method_on_any_instance_of_a_class
  end
  
  def test_should_stub_instance_method_on_any_instance_of_a_class_again
    should_stub_instance_method_on_any_instance_of_a_class
  end
  
  def test_should_stub_two_different_class_methods
    should_stub_two_different_class_methods
  end
  
  def test_should_stub_two_different_class_methods_again
    should_stub_two_different_class_methods
  end
  
  private
  
  def should_stub_module_method
    Thingy.expects(:wotsit).returns(:dooda)
    assert_equal :dooda, Thingy.wotsit
  end
  
  def should_stub_class_method
    widgets = [Widget.new]
    Widget.expects(:find).with(:all).returns(widgets)
    assert_equal widgets, Widget.find(:all)
  end 
  
  def should_stub_two_different_class_methods
    found_widgets = [Widget.new]
    created_widget = Widget.new
    Widget.expects(:find).with(:all).returns(found_widgets)
    Widget.expects(:create).with(:model => 'wombat').returns(created_widget)
    assert_equal found_widgets, Widget.find(:all)
    assert_equal created_widget, Widget.create(:model => 'wombat')
  end
  
  def should_stub_instance_method_on_any_instance_of_a_class
    Widget.any_instance.expects(:model).at_least_once.returns('another_model')
    widget_1 = Widget.new
    widget_2 = Widget.new
    assert_equal 'another_model', widget_1.model
    assert_equal 'another_model', widget_2.model
  end

end