通过 rspec 文档,我在本页http://rubydoc.info/gems/rspec-expectations/frames的 yield 部分找到了这些代码行
任何人都可以逐步解释产生部分中的每一行代码的作用吗
通过 rspec 文档,我在本页http://rubydoc.info/gems/rspec-expectations/frames的 yield 部分找到了这些代码行
任何人都可以逐步解释产生部分中的每一行代码的作用吗
做什么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
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
执行规范的输出:
$ 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
要理解 yield 部分的其他行,类似地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
注意:yield_if_true
第二行中使用的方法似乎从最初定义的地方删除;我通过将其添加到 Order 类中使其工作,如下所示:
class Order
def self.yield_if_true(flag)
yield if flag
end
end