user3007294
user3007294

Reputation: 951

Testing a Set Object with RSpec

*I'm new to testing!

Code:

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

It get the following error:

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

Then, when I just try this:

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

I get:

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

Any idea how I can go about testing this?

*Note: I'm aware I can just use .uniq! to remove duplicates from the array. I am simply using this for an example on how to test Set objects

Upvotes: 0

Views: 187

Answers (1)

osman
osman

Reputation: 2459

In this test you're comparing a Set object to an Array (with a misformed Hash inside of it).

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

You need to create a new set including 1..10 inside of it and compare those.

new_set = (1..10).to_set

and change your expectation

expect(@new_set.remove_duplicates(array)).to eq new_set

You can also test the length of the set to ensure it only contains the expected number of elements.

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

Upvotes: 1

Related Questions