Ruby 中一组数据结构的 TDD 实现

TDD implementation of a set data structure in Ruby

我正在尝试使用 rspec 在 Ruby 中实现集合数据结构。我有一项测试似乎没有通过以下代码:

def add(element)
    if @set_data.include?(element)
        print "This element is already in the set!"
    else
        @set_data += [element]
    end
end

这是对它的测试:

it 'does not add an element if the element is already in the set' do
    set = SetDataStructure.new([1,2,3,4,5])
    set.add(4)
    expect(set).to eq("This element is already in the set!")
end

运行 测试的输出:

......该元素已在集合中!F.

失败:

1) 如果元素已经在集合中,SetDataStructure 不添加元素 Failure/Error: 期望(set.to_a).to eq("This element is already in the set!")

   expected: "This element is already in the set!"
        got: [1, 2, 3, 4, 5]

   (compared using ==)
 # ./spec/set_data_structure_spec.rb:39:in `block (2 levels) in <top (required)>'

在 0.00348 秒内完成 8 个例子,1 个失败

失败的例子:

rspec ./spec/set_data_structure_spec.rb:36 # 如果元素已经在集合中,SetDataStructure 不会添加元素

我也在 GitHub 上发布了代码。

如果有人能启发我,我将不胜感激!

您的期望不正确。

expect(set).to eq("This element is already in the set!")

您的设置保持不变,您不希望它更改为字符串。 这应该是

it 'does not add an element if the element is already in the set' do
  set = SetDataStructure.new([1,2,3,4,5])
  expect { set.add(4) }.to output(/This element is already in the set!/).to_stdout
  # test that set has stayed the  same
  # you probably need to define (override) eq method for SetDataStructure
  expect(set).to eq(SetDataStructure.new([1,2,3,4,5]))
  # alternative is this
  expect(set.set_data).to eq([1,2,3,4,5])
end

Ruby 的集合不会打印任何错误,它只是默默地不向集合添加元素。如果你想要这种行为,那么当你添加 element

时,期望 set 保持不变
it 'does not add an element if the element is already in the set' do
  set = SetDataStructure.new([1,2,3,4,5])
  (1..5).each { |n| set.add(n) }
  expect(set).to eq(SetDataStructure.new([1,2,3,4,5]))
end

如果您确实想要 return 来自 add 方法的字符串以防元素已经存在,您可以按如下方式修改您的方法和测试:

方法:

def add(element)
  if @set_data.include?(element)
    "This element is already in the set!"     # This will not print the statement, but return it
  else
    @set_data += [element]
  end
end

测试:

it 'does not add an element if the element is already in the set' do
  set = SetDataStructure.new([1,2,3,4,5])
  expect(set.add(4)).to eq("This element is already in the set!")
end