【发布时间】: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
【问题讨论】: