所有变量都在Ruby / Rspec中更新而不是一个

时间:2016-07-13 14:51:35

标签: ruby rspec

我一直在测试我在RSpec模块中制作的方法。在比较结果时,我意识到我传递给方法的规范中的变量得到了更新。这是正在测试的方法

def self.location_compact(locations)
  # Find regions 
  regions = locations.select{|l| l.tag == 'Region'}
  # Go through region ids and delete locations with that region as a parent (over 5)
  regions.map(&:id).each do |region_id|
    if locations.count{|location| location.parent_id == region_id} >= 5
      locations.delete_if{|l| l.parent_id == region_id}
    end
  end

  locations.map(&:name).map {|l| l.split.map(&:capitalize)*' '}.map { |e| "#{e}" }
end

这是规范:

let (:regions) { Office.where(tag: 'Region').sample(2) }
let (:locations) { Office.where(tag: 'MC', parent_id: regions.map(&:id)).sample(9) + regions }

context ".location_compact" do
  it "should delete locations that count more than 5 for region" do
    result = GIS::GetResponse.location_compact(locations)
    expect(result).to eq(locations.map(&:name).map {|l| l.split.map(&:capitalize)*' '}.map { |e| "#{e}" })
    expect(result.size).to eq(6)
  end
end

我只希望结果包含更新的数组,而位置也会因某种原因而更新。我认为方法中的变量是孤立的,而不是它更新内存位置本身。将位置复制到另一个varible更新它们......是我总是假设错误,Ruby是如何工作的还是我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

ruby​​中的大多数内容都是通过引用传递的,而不是复制的。数组肯定是其中之一。因此,如果您不想更改它,请dup或不使用破坏性方法(您的delete_if)。