Instantly share code, notes, and snippets.

Embed
What would you like to do?
Red-Green-Refactor by Example Excercise
# Use TDD principles to build out name functionality for a Person.
# Here are the requirements:
# - Add a method to return the full name as a string. A full name includes
# first, middle, and last name. If the middle name is missing, there shouldn't
# have extra spaces.
# - Add a method to return a full name with a middle initial. If the middle name
# is missing, there shouldn't be extra spaces or a period.
# - Add a method to return all initials. If the middle name is missing, the
# initials should only have two characters.
#
# We've already sketched out the spec descriptions for the #full_name. Try
# building the specs for that method, watch them fail, then write the code to
# make them pass. Then move on to the other two methods, but this time you'll
# create the descriptions to match the requirements above.
class Person
attr_reader :first_name, :middle_name, :last_name
def initialize(first_name:, middle_name: :no_name, last_name:)
@first_name = first_name
@middle_name = middle_name
@last_name = last_name
end
def full_name
[first_name, middle_name, last_name]
.reject { |name| name == :no_name }
.join(" ")
end
def full_name_with_middle_initial
[first_name, abbreviate(middle_name), last_name]
.reject { |name| name == :no_name }
.join(" ")
end
def initials
[first_name, middle_name, last_name]
.map { |name| initial(name) }
.reject { |name| name == :no_name }
.join
end
protected
def abbreviate(name)
return name if name == :no_name
initial(name) + "."
end
def initial(name)
return name if name == :no_name
name.chars.first
end
end
RSpec.describe Person do
describe "#full_name" do
it "concatenates first name, middle name, and last name with spaces" do
person = Person.new(
first_name: "John",
middle_name: "Fitzgerald",
last_name: "Kennedy"
)
expect(person.full_name).to eq "John Fitzgerald Kennedy"
end
it "does not add extra spaces if middle name is missing" do
person = Person.new(
first_name: "John",
last_name: "Cena"
)
expect(person.full_name).to eq "John Cena"
end
end
describe "#full_name_with_middle_initial" do
it "abbreviates the middle name" do
person = Person.new(
first_name: "John",
middle_name: "Fitzgerald",
last_name: "Kennedy"
)
expect(person.full_name_with_middle_initial).to eq "John F. Kennedy"
end
it "handles missing middle names" do
person = Person.new(
first_name: "John",
last_name: "Cena"
)
expect(person.full_name_with_middle_initial).to eq "John Cena"
end
end
describe "#initials" do
it "returns the initials" do
person = Person.new(
first_name: "John",
middle_name: "Fitzgerald",
last_name: "Kennedy"
)
expect(person.initials).to eq "JFK"
end
it "handles missing middle names" do
person = Person.new(
first_name: "John",
last_name: "Cena"
)
expect(person.initials).to eq "JC"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment