我是新来的。我正在研究一个带有一些测试的项目。我在编写一个类的规范时遇到了一些问题。我完成了一些简单的规范,但我不知道如何写这个。任何帮助将受到高度赞赏。
我的班级
Class Writer
def initialize(filepath)
@filepath = RAILS_ROOT + filepath
@xml_document = Nokogiri::XML::Document.new
end
def open
File.open(@filepath,"w") do |f|
@gz = Zlib::GzipWriter.new(f)
@gz.write(%[<?xml version="1.0" encoding="UTF-8"?>\n])
@gz.write(%[<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n])
yield self
@gz.write(%[</urlset>])
@gz.close
end
end
def write_entry_to_xml(entry)
node = Nokogiri::XML::Node.new( "url" , @xml_document )
node["loc"] = entry.loc
node["changefreq"] = entry.changfreq
node["priority"] = entry.priority
node["lastmod"] = entry.lastmod
@gz.write(node.to_xml)
end
end
到目前为止我所写的内容如下
describe "writer" do
before :each do
@time = Time.now
@filepath = RAILS_ROOT + "/public/sitemap/test/sitemap_test.xml.gz"
File.open(@filepath,"w") do |f|
@gz = Zlib::GzipWriter.new(f)
end
@xml_document = Nokogiri::XML::Document.new
@entry = Sitemap::Entry.new("location", "monthly", "0.8", @time)
end
describe "open" do
it "should create a file and write xml entries to it" do
end
end
describe "write_entry_to_xml" do
it "should format and entry to xml node and write it" do
node = Nokogiri::XML::Node.new( "url" , @xml_document )
node["loc"].should == @entry.loc
node["changefreq"].should == @entry.changfreq
node["priority"].should == @entry.priority
node["lastmod"].shoul == @entry.lastmod
end
端
任何人都可以帮我编写本课程的完整规范。 提前致谢
答案 0 :(得分:1)
我没有时间为您完成所有这些,但以下是我如何测试代码的示例:
请注意:Ropet::Config.expects(:new).returns(config)
,这可以用于Nokogiri::XML::Node#new
。
我的规格使用RSpec和Mocha,我喜欢这种设置的简单性以及使用这些简单工具可以做些什么。
def write_entry_to_xml(entry)
node = Nokogiri::XML::Node.new( "url" , @xml_document )
node["loc"] = entry.loc
node["changefreq"] = entry.changfreq
node["priority"] = entry.priority
node["lastmod"] = entry.lastmod
@gz.write(node.to_xml)
end
可能是这样的,虽然我不知道你的代码的目的。
it 'writes entry to xml' do
content = double('output')
node = double('node'); node.should_receive(:to_xml).and_return(content);
gz = double('gz'); gz.should_receive(:write).with(content)
w = Writer.new("some_path"); w.open
w.instance_variable_set(:@gz, gz) # i'm guessing @gz is assigned after open only?
entry = # i don't know what entry is
Nokogiri::XML::Node.stub(:new).and_return(node)
node.should_receive(:[]).with("loc", entry.loc)
node.should_receive(:[]).with("changefreq", entry.changefreq)
node.should_receive(:[]).with("priority", entry.priority)
node.should_receive(:[]).with("lastmod", entry.lastmod)
w.write_entry_to_xml(entry)
end