如何在irb中使用RSpec期望值

时间:2013-02-07 10:38:18

标签: ruby rspec irb rspec-expectations

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

~$ 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>'

但它虽然it's a valid case不起作用。我如何使用[1,2,3].should include(1)

1 个答案:

答案 0 :(得分:15)

你已经离我很近了,但是在顶层打电话include你会打电话给Module#include。要绕过它,您需要删除原始的include方法,以便调用RSpec的include

首先让我们弄清楚系统include的来源:

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

确定。它看起来像main中定义的那样。这是Ruby顶级对象。所以让我们重命名并删除原来的include:

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

现在我们可以开展业务了:

> require 'rspec'
> inc RSpec::Matchers
> [1,2,3].should include(1)
=> true