2016-03-07 82 views
0

*我是新來測試!使用RSpec測試設置對象

代碼:

class SetTest 

    def remove_duplicates(array) 
     new_set = Set.new 
     array.each {|number| new_set << number} 
     new_set 
    end 

end 

RSpec的:

describe SetTest do 

    before(:each) do 
    @new_set = SetTest.new 
    end 

    describe '#remove_duplicates' do 
    it 'removes duplicates from an array' do 
     array = [1,2,3,4,5,5,5,5,5,6,7,8,9,10] 
     expect(@new_set.remove_duplicates(array)).to eql([{1,2,3,4,5,6,7,8,9,10}]) 
    end 
    end 

end 

它得到以下錯誤:

syntax error, unexpected ',', expecting tASSOC (SyntaxError)...e_duplicates(array)).to eql({1,2,3,4,5,6,7,8,9,10}) 

然後,當我只是試試這個:

expect(@new_set.remove_duplicates(array)).to eql([1]) 

我得到:

expected: [1] 
got: #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}> 

任何想法,我怎麼能去測試這個?

*注意:我知道我可以使用.uniq!從陣列中刪除重複項。我簡單地使用這個例子來說明如何測試Set對象

回答

1

在這個測試中,你將Set對象與一個Array(內部帶有不正確的Hash)進行比較。

expect(@new_set.remove_duplicates(array)).to eql([{1,2,3,4,5,6,7,8,9,10}]) 

您需要創建一個新的集合,其中包括1..10並對其進行比較。

new_set =(1..10).to_set

,改變你的期望

預期(@ new_set.remove_duplicates(陣列))。到EQ new_set

您還可以測試長度確保它只包含預期的元素數量。

expect(@new_set.remove_duplicates(array).length).to eq 10 
+1

謝謝!這正是我所需要的。欣賞它! – user3007294