gpt4 book ai didi

ruby - 类型错误 : wrong argument type String (expected Module) when trying to use rspec

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:11 26 4
gpt4 key购买 nike

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

我认为我使用的是记录在案的正确语法 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>'

最佳答案

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

>> 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 中 include 匹配器的问题仍然存在(不是 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

对象有一个私有(private)方法include。来自 RSpec::Matchers 的包含方法永远不会有机会被调用。如果你将它包装在一个包含 RSpec::Matchers 的类中,一切都应该有效。

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

关于ruby - 类型错误 : wrong argument type String (expected Module) when trying to use rspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15263862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com