Ruby中的类,对象和setter方法?

时间:2014-03-03 18:48:27

标签: ruby rspec

试图了解如何使用setter methods为什么我在这里失败?我不明白我做错了什么。有人可以解释一下吗?感谢。

class Book
  def title=(title)
    @title = title.capitalize
  end
end

Rspec

describe Book do  
  before do
    @book = Book.new
  end

  describe 'title' do
    it 'should capitalize the first letter' do
      @book.title = "inferno"
      @book.title.should == "Inferno"
    end
  end
end

测试失败:

  

书名应该将第一个字母大写    失败/错误:@ book.title.should ==“Inferno”

     

NoMethodError:

 undefined method `title' for #<Book:0x00000104abd538 @title="Inferno">
 # ./ct.rb:865:in `block (3 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:4)

当你这样做时:

@book.title.should == "Inferno"

您实际上是在title对象上调用Book方法,当然这不存在。您只定义了 setter

您还必须定义 getter

class Book
  def title
    @title
  end

  # ...
end

请注意,有一个用于定义setter和getter的简写:

class Book
  attr_accessor :title
end