Ruby中

时间:2017-01-12 22:41:43

标签: ruby rspec set tdd

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

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不会添加元素      失败/错误:期望(set.to_a).to eq("此元素已经在集合中!")

   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上发布了代码。

如果有人能够启发我,我会非常感激!

2 个答案:

答案 0 :(得分:0)

您的期望不正确。

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的设置不会打印任何错误,它会默默地不添加要设置的元素。如果您想要这种行为,那么当您添加元素

时,期望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

答案 1 :(得分:0)

如果你真的想要从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