我正在開發test-first-ruby-master(你可以在https://github.com/appacademy/test-first-ruby找到它)。測試優先 - 紅寶石13_xml_document
13_xml_document_spec.rb是我的代碼必須通過的Rspec測試。這個測試有幾個任務,但它是我的代碼沒有完成的最後一個(稱爲「縮進」)。
這裏是Rspec的測試:
require "13_xml_document"
describe XmlDocument do
before do
@xml = XmlDocument.new
end
it "renders an empty tag" do
expect(@xml.hello).to eq("<hello/>")
end
it "renders a tag with attributes" do
expect(@xml.hello(:name => "dolly")).to eq('<hello name="dolly"/>')
end
it "renders a randomly named tag" do
tag_name = (1..8).map{|i| ("a".."z").to_a[rand(26)]}.join
expect(@xml.send(tag_name)).to eq("<#{tag_name}/>")
end
it "renders block with text inside" do
expect(@xml.hello { "dolly" }).to eq("<hello>dolly</hello>")
end
it "nests one level" do
expect(@xml.hello { @xml.goodbye }).to eq("<hello><goodbye/></hello>")
end
it "nests several levels" do
xml = XmlDocument.new
xml_string = xml.hello do
xml.goodbye do
xml.come_back do
xml.ok_fine(:be => "that_way")
end
end
end
expect(xml_string).to eq('<hello><goodbye><come_back><ok_fine
be="that_way"/></come_back></goodbye></hello>')
end
it "indents" do
@xml = XmlDocument.new(true)
xml_string = @xml.hello do
@xml.goodbye do
@xml.come_back do
@xml.ok_fine(:be => "that_way")
end
end
end
expect(xml_string).to eq(
"<hello>\n" +
" <goodbye>\n" +
" <come_back>\n" +
" <ok_fine be=\"that_way\"/>\n" +
" </come_back>\n" +
" </goodbye>\n" +
"</hello>\n"
)
end
end
這裏是我的代碼:
class XmlDocument
def initialize(indentation = false)
@indentation = indentation
@counter = 0
end
def method_missing(method, *args, &block)
hash = {}
if block
if @indentation == false
"<#{method}>#{yield}</#{method}>"
elsif @indentation == true
string = ""
string << indent1
string << "<#{method}>\n"
(###)
add_indent
string << indent1
string << yield + "\n"
sub_indent
string << indent2
string << "</#{method}\>"
string
end
elsif args[0].is_a?(Hash)
args[0].map { |key,value| "<#{method.to_s} #{key.to_s}=\"#{value.to_s}\"/>" }.join(" ")
elsif hash.empty?
"<#{method.to_s}/>"
end
end
def indent1
" " * @counter
end
def indent2
" " * @counter
end
def add_indent
@counter += 1
end
def sub_indent
@counter -= 1
end
end
這是輸出我得到了 「縮進」 部分:
<hello>
<goodbye>
<come_back>
+ <ok_fine be="that_way"/>
</come_back>
</goodbye>
</hello>
與正確的答案相反,第四行('ok_fine be =「that_way」/')似乎是靠近左側的兩個縮進比它應該是b即與其餘行不同,第4行不是塊,而是被調用方法'come_back'的一個參數。 我看不到我的錯誤在哪裏。即使在代碼中寫入異常(其中(###)位於我的代碼中)也不會對第4行產生任何影響。
這裏是例外(###):
if args[0].is_a?(Hash)
add_indent
string << indent
arg[0].map{|key, value| string << "<#{method.to_s} #{key.to_s}=\"#{value.to_s}\"/>"}
end
注意:我認爲,如果我設法給第4行縮進的正確的數字,這也將增加的縮進的數量後面的行,所以方法'indent2'將需要修改。