应该期望一个匹配器对象,所以回答您的问题的最简单方法是:
>> require 'rspec-expectations'
=> true
>> s = 'potato'
=> "potato"
>> s.should RSpec::Matchers::BuiltIn::Include.new('tat')
=> true
让我们讨论一下不同的匹配器eq(因为有一些关于include)
>> require 'rspec-expectations'
=> true
>> s = 'potato'
=> "potato"
>> s.should eq('potato')
NoMethodError: undefined method `eq' for main:Object
为了让eq工作,我们可以包含RSpec::Matchers模块(方法定义从第 193 行开始)
>> require 'rspec-expectations'
=> true
>> s = 'potato'
=> "potato"
>> include RSpec::Matchers
>> s.should eq('potato')
=> true
因此,您缺少的是使用 RSpec::Matchers 模块方法扩展对象,或者只是将匹配器传递给 should 方法。
IRB 中包含匹配器的问题仍然存在(不是 100% 确定原因):
>> require 'rspec-expectations'
=> true
>> s = 'potato'
=> "potato"
>> include RSpec::Matchers
>> s.should include('tat')
TypeError: wrong argument type String (expected Module)
它可能与在主对象的上下文中工作有关:
>> self
=> main
>> self.class
=> Object
>> Object.respond_to(:include)
=> false
>> Object.respond_to(:include, true) #check private and protected methods as well
=> true
对象有一个私有方法包括。RSpec::Matchers 中的 Include 方法永远不会有机会被调用。如果你将它包装在一个包含 RSpec::Matchers 的类中,那么一切都应该工作。
Rspec使用 MiniTest::Unit::TestCase RSpec::Matchers(第 168 行)