【发布时间】:2013-08-15 08:23:09
【问题描述】:
我有以下代码:
url = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dpets&field-keywords="
data = Nokogiri::HTML(open(url))
department = data.css('#ref_2619534011')
@department_hash = {}
department.css('li').drop(1).each do | department |
department_title = department.css('.refinementLink').text
department_count = department.css('.narrowValue').text[/[\d,]+/].delete(",").to_i
@department_hash[:department] ||= {}
@department_hash[:department]["Pet Supplies"] ||= {}
@department_hash[:department]["Pet Supplies"][department_title] = department_count
end
所以当我在模板中执行<%= @department_hash %> 时,我会得到:
{:department=>{"Pet Supplies"=>{"Birds"=>15918, "Cats"=>245418, "Dogs"=>513869, "Fish & Aquatic Pets"=>47182, "Horses"=>14774, "Insects"=>358, "Reptiles & Amphibians"=>5834, "Small Animals"=>19806}}}
我为app.rb 创建了一个规范(我正在使用 Sinatra):
app_spec.rb:
require File.dirname(__FILE__) + '/app.rb'
describe "Department" do
it "should scrap correct string" do
expect(@department_hash).to eq '{:department=>{"Pet Supplies"=>{"Birds"=>15918, "Cats"=>245418, "Dogs"=>513869, "Fish & Aquatic Pets"=>47182, "Horses"=>14774, "Insects"=>358, "Reptiles & Amphibians"=>5834, "Small Animals"=>19806}}}'
end
end
但测试失败:
1) Department should scrap correct string
Failure/Error: expect(@department_hash).to eq '{:department=>{"Pet Supplies"=>{"Birds"=>15918, "Cats"=>245418, "Dogs"=>513869, "Fish & Aquatic Pets"=>47182, "Horses"=>14774, "Insects"=>358, "Reptiles & Amphibians"=>5834, "Small Animals"=>19806}}}'
expected: "{:department=>{\"Pet Supplies\"=>{\"Birds\"=>15918, \"Cats\"=>245418, \"Dogs\"=>513869, \"Fish & Aquatic Pets\"=>47182, \"Horses\"=>14774, \"Insects\"=>358, \"Reptiles & Amphibians\"=>5834, \"Small Animals\"=>19806}}}"
got: nil
(compared using ==)
# ./app_spec.rb:5:in `block (2 levels) in <top (required)>'
编辑:
我试过了:
expect(@department_hash[:department]["宠物用品"].keys).to eq '[“鸟”、“猫”、“狗”、“鱼和水生宠物”、“马”、“昆虫”、 “爬行动物和两栖动物”、“小动物”]'
但测试也失败了:
2) 部门应废弃正确的密钥 失败/错误:expect(@department_hash[:department]["Pet Supplies"].keys).to eq '["Birds", "Cats", "Dogs", "Fish & Aquatic 宠物”、“马”、“昆虫”、“爬行动物和两栖动物”、“小动物”]' 无方法错误: '
中未定义的方法[]' for nil:NilClass # ./app_spec.rb:9:inblock(2 级)
可能是什么原因?
【问题讨论】: