我在使用rspec
运行测试时遇到问题。在我的book.rb
文件中,代码块传递给它的所有测试,用于大写书籍标题中的单词(“杀死模仿鸟”,“地狱”)。但是,当我从终端运行rake时,我反复收到错误消息
"Failure/Error: @book.title.should == "Inferno"
ArgumentError:
wrong number of arguments (0 for 1)".
我已经尝试更改了params并删除了title方法,但没有任何效果,即使程序将标题大写,它仍然会收到错误消息。谢谢,非常感谢任何帮助!
class Book
attr_accessor :title, :littlewords
def initialize
@littlewords = ["the", "a", "an", "and", "of", "in"]
end
def title
@title
end
def title(lit)
@title = ''
books = lit.split
books.each do |title|
title.capitalize! unless (littlewords.to_s).include?(title)
end
books[0] = books[0].upcase
books.first.capitalize!
books.join(' ')
end
end
s = Book.new
puts s.title("to kill a mockingbird")
puts s.title("inferno")
答案 0 :(得分:0)
在其他语言中,您可以使用多个名称相同但接受不同参数的方法。在这些语言中,它们实际上是两种不同的方法。
Ruby不是这样的。
当您定义第二个方法title
时,您实际上正在编写第一个方法title
。因此,有一个方法接受一个参数,而不是两个方法,其中一个接受一个参数,一个不接受参数。
所以,当你调用@book.title.should
时,它正在调用期望参数的第二个方法。
首先,您不需要第一个方法title
,因为您在attr_accessor
的开头设置了它。你可以免费获得这种方法。
所以,当你使用:
attr_accessor :title
你得到:
def title
@title
end
def title=(value)
@title = value
end
所以,你要做的是覆盖第二种方法。
attr_reader :title
def title=(lit)
books = lit.split
books.each do |title|
title.capitalize! unless (littlewords.to_s).include?(title)
end
books[0] = books[0].upcase
books.first.capitalize!
@title = books.join(' ')
end
所以你可以这样设置标题:
s = Book.new
puts s.title = "to kill a mockingbird" #=> "To Kill a Mockingbird"
puts s.title = "inferno" #=> "Inferno"
这也可以使您的测试@book.title.should
按预期工作。