rspec中的测试循环返回值

时间:2014-11-06 10:44:27

标签: ruby rspec

我需要测试一个方法,如下所示

class Something
  def test_method
   count = 0
   arr = []
   max = 500
    puts "test_method"
    loop do
      arr += count if count.even?
      count += 1
    end break if count > max
    return arr
  end
end

所以基本上我需要测试test_method()是否返回数组实例并且arr size是否大于3。 但我不想每次都进入这个循环并返回结果。那么在rspec中有什么方法我可以存根最大值并返回数组而不会循环500次。

2 个答案:

答案 0 :(得分:0)

您可以使用class_variable_set方法。

class Something
  @@max = 500

  def test_method
   count = 0
   arr = []

    puts "test_method"
    loop do
      arr += count if count.even?
      count += 1
    end break if count > @@max
    return arr
  end
end

在您的情况下,rspec before_each块可能如下所示:

before(:each) { Something.class_variable_set :@@max, 20 }

您也可以使用instance_variable,如this answer

中所述

答案 1 :(得分:0)

也许可以选择将max作为可选参数传递给该方法?

class Something
  def test_method(max = 500)
    count = 0
    arr = []
    puts "test_method"
    # ...
  end
end