我正在进行一项rails分配,它需要模型中的remove_entry方法和remove_entry的工作测试。我在测试通过时遇到了一些麻烦。有没有人对如何在addressbook.rb中定义remove_entry方法以及如何在entry_spec.rb中编写测试有任何建议?
Entry.rb:
#Load a library called entry.rb
require_relative "entry.rb"
class AddressBook
attr_accessor :entries
def initialize
@entries = []
end
def add_entry(name, phone, email)
#Create a variable index to store
index = 0
@entries.each do |entry|
if name < entry.name
break
end
index += 1
end
@entries.insert(index,Entry.new(name,phone,email))
end
def remove_entry(entry)
@entries.destroy(entry)
end
end
地址簿规范:
RSpec.describe AddressBook do
context "attributes" do
it "should respond to entries" do
book = AddressBook.new
expect(book).to respond_to(:entries)
end
it "should initialize entries as an array" do
book = AddressBook.new
expect(book.entries).to be_a(Array)
end
it "should initialize entries as empty" do
book = AddressBook.new
expect(book.entries.size).to eq 0
end
end
context ".add_entry" do
it "adds only one entry to the address book" do
book = AddressBook.new
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king@lovelace.com')
expect(book.entries.size).to eq 1
end
it "adds the correct information to entries" do
book = AddressBook.new
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king@lovelace.com')
new_entry = book.entries[0]
expect(new_entry.name).to eq 'Ada Lovelace'
expect(new_entry.phone_number).to eq '010.012.1815'
expect(new_entry.email).to eq 'augusta.king@lovelace.com'
end
end
context ".remove_entry" do
it "deletes one entry of the address book" do
book.entries.delete_entry(entry)
expect(book.entries.size).to eq 0
end
end
end
我也有一个entry.rb和entry_spec.rb,但我相信他们删除的方法会在地址簿中,对吗?由于该条目正在从该模型中删除。任何澄清将不胜感激。
答案 0 :(得分:1)
您是remove_entry
方法应该在AddressBook
,因为它正在修改地址簿的entries
集合(以及Entry
} class应该对AddressBook
或其内部结构一无所知。
但是,由于您的add_entry
方法未公开Entry
类,您希望remove_entry
以相同的方式工作,或许通过电子邮件查找条目(哪个应该是唯一的,而不是可能不唯一的名称。所以你可以这样做:
def remove_entry(email)
@entries.delete_if {|entry| entry.email == email}
end
要测试此方法,您可以执行以下操作:
context ".remove_entry" do
it "deletes one entry of the address book" do
book = AddressBook.new
book.add_entry('Ada Lovelace', '010.012.1815', 'augusta.king@lovelace.com')
book.delete_entry('augusta.king@lovelace.com')
expect(book.entries.size).to eq(0)
end
end