testcase.rb

Joshua Yanovski, 04/28/2013 06:32 AM

Download (1.67 KB)

 
1
# Note: this testcase requires RSpec but it is trivial to demonstrate the same behavior without RSpec.
2

    
3
gem "rspec"
4

    
5
RSpec.configure do |c|
6
  c.alias_it_should_behave_like_to :it_has_behavior, 'has behavior:'
7
end
8

    
9
shared_examples "accepts a block" do
10
  def test_block_given
11
    return block_given?
12
  end
13
  
14
  describe "block_given?" do
15
    context "with no block" do
16
      it "returns false" do
17
        call_block_given.should be_false
18
      end
19
    end
20
  
21
    context "with a block" do
22
      it "returns true" do
23
        call_block_given { }.should be_true
24
      end
25
    end
26
  
27
    context "with no block again" do
28
      it "returns false" do
29
        call_block_given.should be_false
30
      end
31
    end
32
  
33
    context "with a block again" do
34
      it "returns true" do
35
        call_block_given { }.should be_true
36
      end
37
    end
38
  end
39
end
40

    
41
describe "method()" do
42
  it_has_behavior "accepts a block" do
43
    alias_method :call_block_given, :test_block_given
44
  end
45
end
46

    
47
describe "method().call()" do
48
  it_has_behavior "accepts a block" do
49
    before (:all) do
50
      @block_given_method = method(:test_block_given)
51
    end
52

    
53
    def call_block_given &block
54
      @block_given_method.call &block
55
    end
56
  end
57
end
58

    
59
describe "method().to_proc().call() (proc recreated for each call)" do
60
  it_has_behavior "accepts a block" do
61
    def call_block_given &block
62
      method(:test_block_given).to_proc.call &block
63
    end
64
  end
65
end
66

    
67
describe "method().to_proc().call() (proc persisted across calls)" do
68
  it_has_behavior "accepts a block" do
69
    before (:all) do
70
      @block_given_method = method(:test_block_given).to_proc
71
    end
72

    
73
    def call_block_given &block
74
      @block_given_method.call &block
75
    end
76
  end
77
end