需要其他方法返回的Rspec测试实例方法(存根?)

时间:2013-02-15 18:30:20

标签: ruby rspec mocking tdd stubbing

我希望那些已经测试过的方法,但我尝试的一切似乎都不符合最佳实践,也不适用。

可能有人可以支持我吗?

要测试的代码

def any_subset_greater?
  divisors_sums.any?{|sum| sum > @value}
end

def no_subset_equal?
  !divisors_sums.any?{|sum| sum == @value}
end

def check_room
  any_subset_greater? && no_subset_equal?
end

RSPEC尝试

首先指定似乎不为divisors方法和实例变量@value设置正确的返回值。

describe "#any_subset_greater?" do
  # Examples:
  # [1,2] > 4   #=> false
  # [1,2,3] > 4 #=> true
  specify "returns true, when value in the array is greater" do
    number.stub(:divisors){[1,2,3]}
    number.stub(:value) {4}
    expect(number.any_subset_greater?).to be_true
  end

end

describe "#no_subset_equal?" do
  # Examples:
  # 4 === [1,2,4]   #=> false
  # 4 === [1,2,3]   #=> false
  # 4 === [1,2,6]   #=> true
end

describe "#check_room" do
  # testing condition from methods above
end

1 个答案:

答案 0 :(得分:1)

不知道你的对象是如何设置的,这个答案只是猜测。我假设你的对象看起来像:

class SpecialNumber
  attr_reader :divisor_sums

  def initialize(n)
    @value = n
    # @divisor_sums is calculated here
  end

  # rest of your methods
end

因此,考虑到这个对象,第一组测试可能如下所示:

subject(:special_number) { SpecialNumber.new 4 }

describe "#any_subset_greater?" do
  context "no divisor sums greater than value" do
    it do
      special_number.stub(:divisor_sums).and_return [1, 2]

      expect(special_number.any_subset_greater?).to be_false
    end
  end

  context "one divisor sum greater than value" do
    it do
      special_number.stub(:divisor_sums).and_return [1, 2, 5]

      expect(special_number.any_subset_greater?).to be_true
    end
  end

  context "several divisor sums greater than value" do
    it do
      special_number.stub(:divisor_sums).and_return [1, 2, 5, 6]

      expect(special_number.any_subset_greater?).to be_true
    end
  end
end

但你不必存根。如果这是一个简单的类,只需每次创建一个新对象,它具有预期的除数:

describe "#any_subset_greater?" do
  context "no divisor sums greater than value" do
    it do
      expect(SpecialNumber.new(3).any_subset_greater?).to be_false
    end
  end
end