通过 rspec 文档,我在本页的 yielding 部分找到了这些代码行 http://rubydoc.info/gems/rspec-expectations/frames
任何人都可以逐步解释 yield 部分中的每一行代码的作用
最佳答案
期望什么{ |b| 5.tap(&b) }.to yield_control
do?
期望 block 中给出的代码调用yield
语句。
block 中给出的代码(即 { |b| 5.tap(&b) }
)调用 ruby 1.9 tap method它的实现中有一个 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
要理解 yielding 部分中的其他行,类似地在 spec 文件中包含 expect
语句,如下所示:
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
关于ruby-on-rails - 这行代码 "expect { |b| 5.tap(&b) }.to yield_control"在功能上实现了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13533439/