【问题标题】:RSpec error: undefined method `include?' for nil:NilClass & undefined method `downcase' for nil:NilClassRSpec 错误:未定义的方法“包括?”对于 nil:NilClass & undefined method `downcase' 对于 nil:NilClass
【发布时间】:2017-11-25 21:13:36
【问题描述】:

我正在学习使用 Ruby 和 RSpec 进行测试驱动开发。我的程序应该在文本中找到给定的单词。第一种情况应该是假的,因为 test_word 以大写字母开头,而第二种情况在小写后应该是真的。但是,当我运行规范文件时,我得到了

undefined methodinclude?'对于 nil:NilClass`

方法和方法

nil:NilClass 的未定义方法 `downcase'

错误。怎么解决?
这是我的代码:

strings_spec.rb:

    require_relative 'strings'

RSpec.describe BasicString do

  before do
    @test_word = "Courage"
    @sentecne = "Success is not final, failure is not fatal: it is the courage to continue that counts!"

    @text = BasicString.new(@sentence)
  end

  context "case-sensitive" do
  it "should output interpolated text" do
    result = @text.contains_word? @test_word

    expect(result).to be_falsey
    end
  end

  context "case-insensitive" do
  it "should output interpolated text" do
    result = @text.contains_word_ignorecase? @test_word# 'text & 'test_word' were made  instance variables when 'before do' block was added.

    expect(result).to be_truthy
    end
  end
end 

strings.rb:

class BasicString
  attr_reader :sentence

  def initialize(sentence)#The constructor that initializes the instance variable @sentence.
    @sentence = sentence
  end

  def contains_word?(test_word)
    @sentence.include? test_word
  end

  def contains_word_ignorecase?(test_word)
    test_word = test_word.downcase#This line downcases the test word.
    @sentence.downcase.include? test_word#This test_word is downcased again for the instance variable to be sure it's downcased.
  end
end

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您的前块中有拼写错误:@sentecne。因此,由于尚未定义 @sentence,因此您最终会使用 nil 值创建字符串。

    【讨论】:

    • 是的!这就是问题所在。现在可以了。需要一双新鲜的眼睛。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    相关资源
    最近更新 更多