首页 文章

RSpec错误:未定义的方法`include? ' for nil:NilClass & undefined method `downcase' for nil:NilClass

提问于
浏览
0

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

未定义的方法包括?'为零:NilClass`

方法和

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

错误 . 怎么能被重新取消?
这是我的代码:

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

1 回答

  • 0

    您在前一个块中有拼写错误: @sentecne . 因此,您最终创建了一个nil值的字符串,因为尚未定义 @sentence .

相关问题