class Crud
$people = { }
def self.add
puts "Enter the name of the person you would like to add in the database."
name = gets.chomp.to_s
if $people[name].nil?
puts "What is #{name}'s age?"
age = gets.chomp.to_i
$people[name] = age.to_i
puts "#{name} has been succesfully added to the database."
else
puts "#{name} already exists in the database. Try again!"
Crud.add
puts $people
end
end
def self.delete
puts "Who would you like to delete from the database? "
count = 1
$people.each do |name, age|
puts "#{count}) #{name}: #{age}"
count += 1
end
name = gets.chomp.to_s
if $people[name.to_s].nil?
puts "User not found. Try again!"
else
$people.delete(name)
puts "#{name} has been deleted from the database."
puts "This is the updated database: "
count = 1
$people.each do |name, age|
puts "#{count}) #{name}: #{age}"
count += 1
end
end
end
def self.read
puts "Updated database:"
puts "-----------------"
count = 1
$people.each do |name, age|
puts "#{count}) #{name}: #{age}"
count += 1
end
puts "-----------------"
end
def self.update
puts "Who would you like to update?"
count = 1
$people.each do |name, age|
puts "#{count}) #{name}: #{age}"
count += 1
end
name = gets.chomp.to_s
if $people[name].nil?
puts "#{name} not found in the database. Try again."
update
else
puts "Type in a new age for #{name} "
age = gets.chomp.to_i
$people[name] = age
puts "#{name}'s age has been updated to #{age}"
puts "This is the updated database: "
count = 1
$people.each do |name, age|
puts "#{count}) #{name}: #{age}"
count += 1
end
end
end
flag = true
while flag == true
puts "What would you like to do?"
puts "1. Add, 2. Update, 3. Delete, 4. Read"
choice = gets.chomp
if choice == "1" || choice == "add"
Crud.add
elsif choice == "2" || choice == "update"
Crud.update
elsif choice == "3" || choice == "delete"
Crud.delete
elsif choice == "4" || choice == "read"
Crud.read
elsif choice == "cancel"
puts "Program has ended"
flag = false
else
puts "ERROR!! Try again"
end
end
所以Ive得到這個代碼,它基本上不會創建一個CRUD(創建,讀取,更新和刪除)系統。
您只能添加與用戶對應的名稱和年齡。
我現在必須對每種方法的代碼進行自動測試。
我不完全確定如何解決問題,沒有適當的教程來做這件事。
到目前爲止,香港專業教育學院得到這個測試add方法
require "okok.rb"
require "test/unit"
class Test < Test::Unit::TestCase
def test_add()
add = Crud.new()
assert_equal...
end
末
試試這個https://learnrubythehardway.org/book/ex47.html – aledustet
它有點令人困惑,一個 – User983
這將是很難測試,因爲'gets'這將等待用戶輸入。我所建議的是將課堂分爲兩個「純」類,它接受輸入併產生輸出,這是可測試的。然後有第二個類,它實際上是包含'gets'和'puts'的用戶界面,調用第一個類來完成實際的工作。 – Kris