我正在阅读 RSpec,并试图弄清楚 RSpec 的“应该”是如何实现的。
有人可以帮忙解释一下这个函数的元性质是如何工作的吗?
代码位于此处:
http://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb http://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb
TIA,
-daniel
澄清:
target.should == 5
target 的值是如何传递给“should”的,而“should”又是“==”对应 5 的?
看一眼类运算符匹配器 http://github.com/dchelimsky/rspec/blob/master/lib/spec/matchers/operator_matcher.rb.
这一切都归结为 Ruby 允许您省略句点和括号。你真正写的是:
target.should.send(:==, 5)
也就是发送消息should
到对象target
,然后发送消息==
无论什么should
返回。
方法should
猴子被修补成Kernel
,所以它可以被任何对象接收。这Matcher
由返回should
持有actual
在这种情况下是target
.
The Matcher
实现该方法==
与expected
在本例中,是数字 5。您可以自己尝试一下简化示例:
module Kernel
def should
Matcher.new(self)
end
end
class Matcher
def initialize(actual)
@actual = actual
end
def == expected
if @actual == expected
puts "Hurrah!"
else
puts "Booo!"
end
end
end
target = 4
target.should == 5
=> Booo!
target = 5
target.should == 5
=> Hurrah!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)