Reputation: 8086
Trying to understand how to use setter methods
Why am I getting a failure here? I don't understand what I'm doing wrong. Can someone please explain? Thanks.
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
Test Failure:
Book title should capitalize the first letter Failure/Error: @book.title.should == "Inferno"
NoMethodError:
undefined method `title' for #<Book:0x00000104abd538 @title="Inferno"> # ./ct.rb:865:in `block (3 levels) in <top (required)>'
Upvotes: 0
Views: 181
Reputation: 33626
When you do:
@book.title.should == "Inferno"
you are essentially calling the title
method on a Book
object, which of course does not exist. You only defined the setter.
You also have to define the getter:
class Book
def title
@title
end
# ...
end
Note that there is a shorthand for defining both the setter and the getter:
class Book
attr_accessor :title
end
Upvotes: 4