Ruby元编程,RSpec的“应该”如何工作?
我正在阅读RSpec,我试图弄清楚RSpec的“应该”是如何实现的。
有人可以提一下这个函数的元性质是如何工作的吗?
代码位于:
http://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb
TIA,
-daniel
澄清:
target.should == 5
目标的价值是如何传递给“应该”的,而这又是“==”与5的对比?
看一下OperatorMatcher类 。
这一切都归结为Ruby允许您省略句点和括号。 你真正写的是:
target.should.send(:==, 5)
也就是说,将消息发送到对象target
,然后将消息==
发送到should
返回的内容。
该方法should
猴子修补到Kernel
,因此它可以被任何对象接收。 返回的Matcher
should
保存actual
,在这种情况下是target
。
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!