代码之家  ›  专栏  ›  技术社区  ›  Daniel

Ruby元编程,RSpec的'should'是如何工作的?

  •  13
  • Daniel  · 技术社区  · 16 年前

    我在读RSpec,我想弄清楚RSpec的“应该”是如何实现的。

    有人能帮我解释一下这个函数的元本质是如何工作的吗?

    代码位于此处:

    http://github.com/dchelimsky/rspec/blob/master/lib/spec/expectations/extensions/kernel.rb

    蒂亚,

    -丹尼尔

    target.should == 5
    

    1 回复  |  直到 10 年前
        1
  •  27
  •   Bryan Ash    10 年前

    class OperatorMatcher .

    target.should.send(:==, 5)
    

    也就是说,发送消息 should 到对象 target ,然后发送消息 == 应该

    方法 猴子被补上了吗 Kernel ,因此它可以被任何对象接收。这个 Matcher 退回人 应该 actual 目标 .

    匹配器 实现方法 == 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!
    
    推荐文章