3

检查字符串中子字符串的包含情况。

我认为我使用了此处记录的正确语法,但它对我不起作用。我错过了什么?

>> require 'rspec-expectations'
=> true
>> s = 'potato'
=> "potato"
>> s.include?('tat')
=> true
>> s.should include('tat')
TypeError: wrong argument type String (expected Module)
    from (irb):4:in `include'
    from (irb):4
    from /usr/bin/irb:12:in `<main>'
4

2 回答 2

3

应该期望一个匹配器对象,所以回答您的问题的最简单方法是:

>> 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 行)

于 2013-03-07T22:33:26.300 回答
1

您需要围绕期望设置一个context或块。it

于 2013-06-06T23:37:49.230 回答