TypeError:错误的参数类型String(预期模块)在尝试使用rspec时

时间:2013-03-07 05:34:51

标签: ruby string rspec

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

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

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

2 个答案:

答案 0 :(得分:3)

应该期望匹配器对象以最简单的方式回答您的问题:

>> require 'rspec-expectations'
=> true
>> s = 'potato'
=> "potato"
>> s.should RSpec::Matchers::BuiltIn::Include.new('tat')
=> true

让我们谈谈不同的匹配器 eq (因为有一些关于包括

>> 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模块方法扩展你的对象,或者只是将matcher传递给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

对象有一个私有方法include。来自RSpec :: Matchers的包含方法永远不会有被调用的机会。如果你将它包装在一个包含RSpec :: Matchers的类中,那么每个都应该正常工作。

Rspec使用MiniTest :: Unit :: TestCase RSpec::Matchers(第168行)

答案 1 :(得分:1)

您需要围绕期望contextit阻止。