How to use RSpec expectations in irb

落花浮王杯 提交于 2019-11-29 02:52:36

问题


I'd want to use [1,2,3].should include(1) in irb. I tried:

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

But it doesn't work though it's a valid case. How can I use [1,2,3].should include(1)?


回答1:


You are close, but calling include on top-level you will be calling Module#include. To get around it you need to remove the original include method so that RSpec's include gets called instead.

First let's figure out where the system include comes from:

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

Ok. It looks like it's defined in main. This is the Ruby top-level object. So let's rename and remove the original include:

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

Now we can get down to business:

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


来源:https://stackoverflow.com/questions/14749047/how-to-use-rspec-expectations-in-irb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!