what does this line of code "expect { |b| 5.tap(&b) }.to yield_control" implementing functionally?

Amr*_*rut 1 ruby ruby-on-rails rspec-rails

Going through the rspec docs i found these lines of code in yielding section of this page http://rubydoc.info/gems/rspec-expectations/frames

任何人都可以解释屈服部分中每行代码的步骤

Pra*_*thy 5

怎么expect { |b| 5.tap(&b) }.to yield_control办?

期望块中给出的代码调用 yield语句.

块中给出的代码(即{ |b| 5.tap(&b) })调用ruby 1.9 tap方法,该方法有一个yield在其实现中语句.

所以该声明实际上断言ruby 1.9的tap方法有一个yield声明.:-)

要更好地理解此语句,请尝试以下代码示例:

order.rb 文件

class Order
end
Run Code Online (Sandbox Code Playgroud)

order_spec.rb 文件

require 'rspec-expectations'
require './order'

describe Order do
  it "should yield regardless of yielded args" do
    expect { |b| 5.tap(&b);puts "The value of b is #{b.inspect}" }.to yield_control
  end
end 
Run Code Online (Sandbox Code Playgroud)

执行规范的输出:

$ rspec yield_spec.rb

Order
The value of b is #<RSpec::Matchers::BuiltIn::YieldProbe:0x000001008745f0 @used=true, @num_yields=1, @yielded_args=[[5]]>
  should yield regardless of yielded args

Finished in 0.01028 seconds
1 example, 0 failures
Run Code Online (Sandbox Code Playgroud)

要理解"屈服"部分中的其他行,请expect在spec文件中包含以下语句,如下所示:

 it "should yield with no args" do
    expect { |b| Order.yield_if_true(true, &b) }.to yield_with_no_args
  end 
      it "should yield with 5 args" do
    expect { |b| 5.tap(&b) }.to yield_with_args(5)
  end 

  it "should yield with integer args" do
    expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum)
  end 

  it "should yield with string args" do        
    expect { |b| "a string".tap(&b) }.to yield_with_args(/str/)
  end 

  it "should yield 1,2,3 successively" do
    expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3)
  end 

  it "should yield ([:a,1], [:b,2]) successively" do
    expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2]) 
  end 
Run Code Online (Sandbox Code Playgroud)

注意:yield_if_true第二行中使用的方法似乎从最初定义的位置删除; 我把它添加到Order类中,如下所示:

class Order
  def self.yield_if_true(flag)
    yield if flag
  end
end
Run Code Online (Sandbox Code Playgroud)