11

我想[1,2,3].should include(1)在irb中使用。我试过:

~$ irb
1.9.3p362 :001 > require 'rspec/expectations'
 => true 
1.9.3p362 :002 > include RSpec::Matchers
 => Object 
1.9.3p362 :003 > [1,2,3].should include(1)
TypeError: wrong argument type Fixnum (expected Module)
    from (irb):3:in `include'
    from (irb):3
    from /home/andrey/.rvm/rubies/ruby-1.9.3-p362/bin/irb:16:in `<main>'

但它不起作用,虽然它是一个有效的案例。我该如何使用[1,2,3].should include(1)

4

1 回答 1

15

你很接近,但include在顶层调用你将调用Module#include. 要解决它,您需要删除原始的 include 方法,以便include调用 RSpec。

首先让我们弄清楚系统include来自哪里:

> method :include
=> #<Method: main.include>

行。看起来它是在main. 这是 Ruby 顶级对象。因此,让我们重命名并删除原始包含:

> class << self; alias_method :inc, :include; remove_method :include; end

现在我们可以开始谈正事了:

> require 'rspec'
> inc RSpec::Matchers
> [1,2,3].should include(1)
=> true
于 2013-02-07T13:43:54.953 回答