Ruby元编程,RSpec的“应该"如何工作? [英] Ruby metaprogramming, how does RSpec's 'should' work?

查看:55
本文介绍了Ruby元编程,RSpec的“应该"如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读RSpec,并且试图弄清楚RSpec的应该"是如何实现的.

I was reading up on RSpec and I was trying to figure out how RSpec's "should" was implemented.

有人可以帮忙此功能的元性质如何工作吗?

Could someone give a hand on how the meta nature of this function works?

代码位于此处:

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

TIA,

-丹尼尔

说明:

target.should == 5

目标值是如何传递给应该"的,而应该"又是"==对5"?

How did target's value get passed along to "should", which in turn was "=="'d against 5?

推荐答案

看看这一切都归结为Ruby,您可以省略句点和括号.您真正在写的是:

It all boils down to Ruby allowing you to leave out periods and parenthesis. What you are really writing is:

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

也就是说,将消息should发送到对象target,然后将消息==发送到should返回的任何对象.

That is, send the message should to the object target, then send the message == to whatever should returns.

方法should被猴子修补到Kernel中,因此它可以被任何对象接收. should返回的Matcher保留actual,在这种情况下为target.

The method should is monkey patched into Kernel, so it can be received by any object. The Matcher returned by should holds the actual which in this case is target.

Matcher实现了方法==,该方法与expected进行比较,在这种情况下,该数字是5.一个可以尝试的简化示例:

The Matcher implements the method == which does the comparison with the expected which, in this case, is the number 5. A cut down example that you can try yourself:

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!

这篇关于Ruby元编程,RSpec的“应该"如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆