【发布时间】:2013-03-02 19:49:56
【问题描述】:
我在向 ruby on rails 中的哈希添加新键和值时遇到问题。该方法看起来像这样,带有两个调试打印,并且应该简单地添加索引 + 1 作为值的提供程序键,以便稍后访问具有正确 ID 的提供程序。
search_result.each_with_index do |articles, index|
puts "merge-articles: #{articles}"
articles.each{ |article| article[:provider] = index + 1;}
puts "merge-articles(later): #{articles}"
end
我从 puts 中得到了那些输出,在我看来这看起来相当不错:
merge-articles: [{:ean=>"9780234474278", :author=>"Dan Brown", :name=>"The Da Vinci Code", :price=>19.65, :image=>"www.google.de/image.png"}]
merge-articles(later): [{:ean=>"9780234474278", :author=>"Dan Brown", :name=>"The Da Vinci Code", :price=>19.65, :image=>"www.google.de/image.png", :provider=>2}]
仅测试密钥是否存在的规范会出现此错误:
Failure/Error: HomeController.merge(@no_same_items_merge).each do |item|
TypeError:
can't convert Symbol into Integer
# ./app/controllers/home_controller.rb:41:in `[]='
# ./app/controllers/home_controller.rb:41:in `block (2 levels) in merge'
# ./app/controllers/home_controller.rb:41:in `each'
# ./app/controllers/home_controller.rb:41:in `block in merge'
# ./app/controllers/home_controller.rb:39:in `each'
# ./app/controllers/home_controller.rb:39:in `each_with_index'
# ./app/controllers/home_controller.rb:39:in `merge'
# ./spec/controllers/home_controller_spec.rb:104:in `block (5 levels) in <top (required)>'
编辑:RSpec 测试如下所示:
it "should return an array of right formatted hashes" do
HomeController.merge(@no_same_items_merge).each do |item|
item.should have_key(:name)
item.should have_key(:ean)
item.should have_key(:author)
item.should have_key(:description)
item.should have_key(:url)
item.should have_key(:prices)
item.should have_key(:images)
end
end
感谢您的帮助!
【问题讨论】:
-
你能粘贴到 rspec 测试中吗?可能是那里的问题,而不是代码中的问题。
-
该错误强烈暗示在规范中,
article是Array,而不是Hash;检查您如何在规范中定义article。 -
@bloopletech 是对的,
article是Array的Hash。 -
啊,我发现我的错误,我用错误的参数进行测试
标签: ruby-on-rails ruby ruby-on-rails-3 hash