How to delete an entire array in Ruby and test with RSpec -
i'm new ruby , taking full stack course. 1 of projects building addressbook. have set how add entry addressbook, however, can't seem figure out how delete entry (i make attempt remove_entry method in addressbook class below not having luck). supposed test first rspec, have test fail , write code pass. if didn't include info needed question let me know (rookie here). anyway, here have far:
rspec
context ".remove_entry" "removes 1 entry address book" book = addressbook.new entry = book.add_entry('ada lovelace', '010.012.1815', 'augusta.king@lovelace.com') book.remove_entry(entry) expect(entry).to eq nil end end
addressbook class
require_relative "entry.rb" class addressbook attr_accessor :entries def initialize @entries = [] end def add_entry(name, phone, email) index = 0 @entries.each |entry| if name < entry.name break end index += 1 end @entries.insert(index, entry.new(name, phone, email)) end def remove_entry(entry) @entries.delete(entry) end end
entry class
class entry attr_accessor :name, :phone_number, :email def initialize(name, phone_number, email) @name = name @phone_number = phone_number @email = email end def to_s "name: #{@name}\nphone number: #{@phone_number}\nemail: #{@email}" end end
when testing code rspec receive following error message:
.....f failures: 1) addressbook.remove_entry removes 1 entry address book failure/error: expect(entry).to eq nil expected: nil got: [#<entry:0x00000101bc82f0 @name="ada lovelace", @phone_number="010.012.1815", @email="augusta.king@lovelace.com">] (compared using ==) # ./spec/address_book_spec.rb:49:in `block (3 levels) in <top (required)>' finished in 0.02075 seconds (files took 0.14221 seconds load) 6 examples, 1 failure failed examples: rspec ./spec/address_book_spec.rb:44 # addressbook.remove_entry removes 1 entry address book
just test book.entries association empty:
expect(book.entries).to be_empty
as book local variable in test, not false negative result if keep test atomic. best practices on rspec.
edit: can check entry not in set:
expect(book.entries.index(entry)).to be_nil
or test change of array length with:
expect { book.remove_entry(entry) }.to change{book.entries.count}.by(-1)
if wonder be_xxx
syntax sugar, if object respond xxx?
, can use be_xxx
in tests (predicate matchers)
Comments
Post a Comment